天天看點

python重點文法總結(二)----@操作符

2、@操作符

@符号用于修飾函數,該修飾符後面接一個函數名後,在第下一行再接一個函數定義,這個函數定義可以是子產品或類方法,不允許修飾類。修飾符@加一個函數名相當于該函數,同時将後面修飾的函數作為參數傳遞,需要傳回一個可以調用的函數,并且這個傳回的函數與修飾的函數名同名。下面通過幾個執行個體進行解釋:

執行個體1:

def decorator(decorated_function):

    print("hello, wang shuo")

@decorator

def decorated_funciton(a,b):

    print(a+b)

輸出:

hello, wang shuo

修飾函數在定義時就會執行,因為前面說道@後面的函數會将修飾的函數decorated_function作為參數,同時傳回一個可以調用的函數,這個傳回的函數與修飾的函數同名。是以在定義時就要執行,因為需要傳回一個可調用的函數。是以,在定義時執行了print("hello, wang shuo"),但是,由于沒有傳回可以調用的東西,是以通過@修飾後就沒有可以調用的東西,調用decorated_function(a,b)是不行的,因為通過@修飾後它代表的是decorator傳回的内容,由于沒有傳回,也就無法調用,是以這種情況調用decorated_function(3,4)會報錯。TypeError: 'NoneType' object is not callable

執行個體2:

def decorator(decorated_function):

    print("hello, wang shuo first time")

    def actual_function(*args):

        print("hello,wang shuo second time")

    return actual_function

@decorator

def decorated_function(a,b):

    print(a+b)

print("meet wang shuo")

decorated_function(2,3)

輸出:

hello, wang shuo first time

meet wang shuo

hello,wang shuo second time

這裡首先輸出了“hello, wang shuo first time”,說明在執行print之前就執行了decorator函數中的内容,該函數傳回一個可以調用的内容,即actual_function,于是,被@修飾過的函數就變成了這個actual_fuction,于是在調用decorated_function(2,3)時依然輸出“hello,wang shuo second time”,即actual_function中的内容。

執行個體3:

def decorator(dec_fun):

    print("hello, wang shuo first time")

    def actual_function(*args):

        print("hello,wang shuo second time")

        dec_fun(*args)

    return actual_function

@decorator

def decorated_function(a,b):

    print(a+b)

print("meet wang shuo")

decorated_function(2,3)

輸出:

hello, wang shuo first time

meet wang shuo

hello,wang shuo second time

5

可以看到這次輸出了a+b的内容,這是因為在actual_function中調用的被修飾的函數,因為被修飾的函數作為參數傳遞給函數decorator,而在傳回的函數中調用了這個函數dec_fun(*args),是以在使用decorated_function過程中也會使用該函數的功能。

總結:

通過@修飾的函數能夠執行那些内容不是看被修飾函數的内容,而是需要看用來修飾的函數的内容,即decorator,它的傳回可調用的内容才是最終的執行函數,在調用這個被修飾的函數(decorated_function)時,就會調用decortor傳回的可調用的部分。