閉包函數,裝飾器

来源:https://www.cnblogs.com/setcreed/archive/2019/09/23/11575123.html
-Advertisement-
Play Games

[TOC] 閉包函數 什麼是閉包函數 閉包函數把 閉包函數內的變數 + 閉包函數內部的函數, 這兩者包裹起來,然後通過返回值的形式返回出來。 定義在函數的內函數 該函數體代碼包含對該函數外層作用域中變數的引用 函數外層指的不是全局作用域 上述代碼中,f是一個全局的名字,但f拿到了inner的記憶體地址 ...


目錄

閉包函數

什麼是閉包函數

閉包函數把 閉包函數內的變數 + 閉包函數內部的函數, 這兩者包裹起來,然後通過返回值的形式返回出來。

  • 定義在函數的內函數
  • 該函數體代碼包含對該函數外層作用域中變數的引用
  • 函數外層指的不是全局作用域
def outter():
    x = 10
    def inner():
        print(x)
    return inner

f = outter()  # f=inner
f()
print(f)

# 列印結果:
10
<function outter.<locals>.inner at 0x00000201011A7840>

上述代碼中,f是一個全局的名字,但f拿到了inner的記憶體地址。將一個定義在內部的函數返回出來,在全局拿到f,這個f是全局變數,這樣就打破了函數的層級限制,能在任意位置使用內部的函數

閉包函數的應用

以參數的方式傳值

import requests

def get(url):
    response = requests.get(url)
    print(response.text)

get('https://www.baidu.com')

這裡寫了一個爬蟲函數,爬取百度的首頁。但這樣的問題就是每次想爬百度,或者其他網站都要傳一堆網址,比較麻煩,所以可以用閉包函數解決。

傳值另一方式: 包給函數

import requests

def spider(url):
    def get():
        response = requests.get(url)
        print(response.text)
    return get

baidu = spider('https://www.baidu.com')
baidu()

taobao = spider('https://www.taobao.com')
taobao()

這樣就很方便,以後調baidu,直接baidu()就行了

裝飾器

什麼是裝飾器

裝飾器就是 為需要裝飾的函數新增了一個額外的功能,裝飾器的本質就是一個 給函數增加功能的函數。

為什麼要裝飾器

裝飾器,增加功能需要註意以下幾點:

  • 不改變原函數的原代碼
  • 不改變原函數的調用方式

使用無參裝飾器

import time

def index():
    '''被裝飾函數'''
    time.sleep(1)
    print('welcome to index')

index()

需要為上面的函數新增加一個功能,能夠統計函數運行的時間

在原代碼上修改

import time

def index():
    start = time.time()
    time.sleep(1)
    print('welcome to index')
    end = time.time()
    print(f'run time is {end - start}')

index()

這樣就違反了不能修改原代碼這一原則

import time

def index():
    time.sleep(1)
    print('welcome to index')

start = time.time()
index()
end = time.time()
print(f'run time is {end - start}')

這樣寫就不是裝飾器,因為裝飾器是一個函數

利用函數傳參方式

import time

def index():
    '''被裝飾函數'''
    time.sleep(1)
    print('welcome to index')

def time_count(func):
    start = time.time()
    func()
    end = time.time()
    print(f'run time is {end - start}')

time_count(index)

雖然實現了,但改變了函數調用方式

利用閉包

import time

def index():
    '''被裝飾函數'''
    time.sleep(1)
    print('welcome to index')

def deco(func):  # func = index 最初的index
    def time_count():
        start = time.time()
        func()
        end = time.time()
        print(f'run time is {end - start}')
    return time_count

# f = deco(index)   

index = deco(index)   # index = time_count
index()

這樣就簡單實現了一個裝飾器函數,調用index不是調用最初的index了,而是調用time_count函數,但用戶不知道,看起來就和原來使用一樣

裝飾器完善

上述的裝飾器,最後調用index()的時候,其實是在調用time_count(),因此如果原始的index()有返回值的時候,time_count()函數的返回值應該和index()的返回值相同,也就是說,我們需要同步原始的index()和time_count()方法的返回值。

import time

def index():
    '''被裝飾函數'''
    time.sleep(1)
    print('welcome to index')
    return 1234

def deco(func):
    def time_count():
        start = time.time()
        res = func()
        end = time.time()
        print(f'run time is {end - start}')
        return res

    return time_count

# index = deco(index)   # index = time_count
# index()
res = index()
print(res)

給原始index傳參

import time

def index(x):
    '''被裝飾函數'''
    time.sleep(1)
    print('welcome to index')
    return 1234

def deco(func):
    def time_count(*args,**kwargs):
        start = time.time()
        res = func(*args,**kwargs)
        end = time.time()
        print(f'run time is {end - start}')
        return res

    return time_count

index = deco(index)   # index = time_count
index(10)

使用裝飾器語法糖

import time


def deco(func):
    def time_count(*args, **kwargs):
        start = time.time()
        res = func(*args, **kwargs)
        end = time.time()
        print(f'run time is {end - start}')
        return res

    return time_count


@deco    # 這裡就相當於 index = deco(index)
def index(x):
    '''被裝飾函數'''
    time.sleep(1)
    print('welcome to index')
    return 1234


index(10)

裝飾器模板

def deco(func):
    def wrapper(*args,**kwargs):
        # 這裡加功能
        res = func(*args,**kwargs)
        return res
    
    return wrapper

裝飾器小練習

# 寫一個登錄裝飾器,裝飾猜年齡,登錄了才能玩猜年齡

username_list = []

def guess(age):
    print('welcome to guess age')
    age_inp = input('請猜年齡').strip()
    age_inp = int(age_inp)

    if age_inp == age:
        print('bingo')
    elif age_inp < age:
        print('猜小了')
    else:
        print('猜大了')


def login(func):
    def wrapper(*args,**kwargs):
        if username_list:
            print('已登錄,請勿重覆登錄')
            res = func(*args, **kwargs)
            return res

        username_inp = input('請輸入用戶名:').strip()
        pwd_inp = input('請輸入密碼:').strip()

        with open('user_info.txt', 'r', encoding='utf-8') as fr:
            for user_info in fr:
                user_info = user_info.strip()
                username, pwd = user_info.split(':')

                if username_inp == username and pwd_inp == pwd:
                    print('登錄成功')
                    username_list.append(username_inp)
                    res = func(*args, **kwargs)
                    return res

                else:
                    print('登錄失敗')

        res = func(*args,**kwargs)
        return res

    return wrapper

guess = login(guess)
guess(19)

有參裝飾器

import time

def outter(age):
    def deco(func):
        def wrapper(*args,**kwargs):
            if age >= 18:
                print('成年了')
            else:
                print('未成年')

            start = time.time()
            res = func(*args,**kwargs)
            end = time.time()
            print(f'run time is {end - start}')
            return res

        return wrapper

    return deco

@outter(19)  #   相當於 deco = outter(19)   index = deco(index)
def index():
    '''被裝飾函數'''
    time.sleep(1)
    print('welcome to index')

index()

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 2019-09-23-23:48:00 今日所學的內容有: ...
  • 一、預設配置文件 二、指定配置文件 三、使用profile指定配置 ...
  • 在上篇文章: "SpringBoot源碼解析:創建SpringApplication對象實例" 中,我們詳細描述了SpringApplication對象實例的創建過程,本篇文章繼續看 方法的執行邏輯吧 1. 第一行使用了 來記錄開始時間 2. 設置了 環境變數,在網上瞭解了一下這個變數的相關信息 H ...
  • [TOC] 1. 數組操作符重載 數組操作符重載 通過重載數組操作符,可以使類的對象支持數組的下標訪問 數組操作符只能重載為類的成員函數 重載函數能且僅能使用一個參數,也就是數組下標 可以定義不同參數的多個重載函數 在重載數組操作符時,要記得數組操作符的原生語義——數組訪問和指針運算。 cpp / ...
  • 從今天起,我會在這裡記錄一下學習深度學習所留下的足跡,目的也很簡單,手頭有近3w個已經標記好正確值得驗證碼,想要從頭訓練出一個可以使用的模型, 雖然我也知道網上的相關模型和demo很多,但是還是非常希望自己可以親手搞一個能用的出來,學習書籍主要是:李金洪老師的《深度學習之Tensorflow 入門、 ...
  • 在做數據分析的過程中,經常會遇到文件的讀取。我想很多人都在這個環節遇到過問題,所以就把自己掌握的一些文件讀取方法記錄下來,以及過程中遇到的一些狀況和解決方法列出來,以便交流。 open open() 函數用於創建或打開指定文件,該函數的語法格式如下: 參數說明: file:表示要創建的文件對象。 f ...
  • 實在不想看JVM了。刷幾道劍指Offer的題,今天就水一水吧,腦子迷糊。 1.二維數組中的查找 在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。 解題思路: ...
  • 一、題目 二、思路 1、dfs 實驗要求用多種思路完成,所以一開始就沿用了上一個實驗馬走棋盤的思路,添加了鄰接矩陣來記錄有向網的權值。總體思路還是DFS遍歷搜索。 過程剪枝: 1、因為要求為最短路徑,而一般情況總會存在多條可行路徑,在判斷過程中需要走過每一條路徑才能知道該路徑的長度,但如果已知一條可 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...