1. 程式人生 > >Python中@符號的用法-1

Python中@符號的用法-1

       首先參考了幾篇網路上的文章或者教程,看完之後也沒有弄明白這個功能是什麼意思。於是查了一下Python的文件,相關的描述如下:

A function definition may be wrapped by one or more decorator expressions. Decorator expressions areevaluated when the function is defined, in the scope that contains the functiondefinition. The result must be a callable, which is invoked with the functionobject as the only argument. The returned value is bound to the function nameinstead of the function object. Multiple decorators are applied in nestedfashion. For example, the following code

@f1(arg)

@f2

def func(): pass

is roughly equivalent to

def func(): pass

func = f1(arg)(f2(func))

       其實,太多的東西也沒必要去理解了。直接按照這個例子來理解一下就好了。這樣,假如有以下程式碼:

def Func1(par):

       print("Func1")

       print(par)

def Func2(par):

       print("Func2")

       print(par)

@Func1

@Func2

def Func3():

       print("Func3")

       return 9

       相應的修飾部分等效結果應該如下:

Func3 =Func1(Func2(Func3))

       先執行這段程式碼看一下結果:

E:\01_workspace\02_programme_language\03_python\OOP\2017\08\10>pythondemo.py

Func2

<function Func3at 0x00000201330A3510>

Func1

None

       然後修改程式碼如下:

def Func1(par):

       print("Func1")

       print(par)

def Func2(par):

       print("Func2")

       print(par)

#@Func1

#@Func2

def Func3():

       print("Func3")

       return 9

Func3 =Func1(Func2(Func3))

程式執行結果:

E:\01_workspace\02_programme_language\03_python\OOP\2017\08\10>pythondemo.py

Func2

<function Func3at 0x000002240ABE3510>

Func1

None

       從上面的結果看,兩個版本的程式碼執行效果是相同的。而修飾符號的作用其實是直接運行了程式碼中被修飾的函式,而且按照修飾的層級進行了引數傳遞。好奇呼叫了一下Fun3,出現一下提示:

Traceback (mostrecent call last):

  File "demo.py", line 20, in<module>

    Func3()

TypeError:'NoneType' object is not callable

       由此看來,是不是可以理解為被修飾的函式最終的函式體都等同於pass,而相應的函式還是一個不可被呼叫的函式。這樣看來的話,這樣的功能作用也不是很大。

       通過查詢資料,這樣的功能還能夠用於修飾類,具體的用法以後再做一下小結。