The @ symbol has a special meaning in the Python language and is used as a modifier.
For details, refer to the following
Code :
# ! /Usr/bin/ENV Python
# Coding = UTF-8
From Time Import Ctime, sleep
Def Tcfunc (func ):
Def Wrappedfunc ():
Print ' [% S] % s () called ' % (
Ctime (), func)
Return Func ()
Print " In tcfunc called "
Print " Wrapped func % s " % Wrappedfunc
Return Wrappedfunc
# Decorator only calls the tcfunc function, which uses Foo as a parameter and returns
# Wrappedfunc function object. This object is used to replace calls of the foo function externally.
# The defined function can only be called internally, and the call method cannot be obtained externally !!
@ Tcfunc # Call sequence is: tcfunc (func) --> wrappedfunc --> func
Def Foo ():
Print " In Foo called "
Pass
Print "Foo FUNC: % s" %Foo
Foo ()
Print "-"*100
Sleep (4)
ForIInRange (2):
Sleep (I)
Foo ()
Print "-"*100
In the above function, tcfunc defines a function, which is embedded with a function that requires a func parameter.
@ Tcfunc indicates that the function name defined below is called by tcfunc as a tcfunc parameter.
Code: @ Tcfunc
DefFoo ():
Pass
When defined, it is called by tcfunc, that is, tcfunc (FOO). This function returns a wrappedfunc object, and the defined Foo function name object has been replaced by the wrappedfunc object, the function defined by foo () is used only as a parameter within the tcfunc function! We can print their addresses to check whether the Foo and wrappedfunc externally called by tcfunc are the same object:
In tcfunc called
Wrapped func <function wrappedfunc at 0x01a3dd30>
Foo FUNC: <function wrappedfunc at 0x01a3dd30>
[Thu Jan 08 00:04:35 2009] <function Foo at 0x01a3dcf0> () called
In Foo called
Bytes ----------------------------------------------------------------------------------------------------
[Thu Jan 08 00:04:39 2009] <function Foo at 0x01a3dcf0> () called
In Foo called
Bytes ----------------------------------------------------------------------------------------------------
[Thu Jan 08 00:04:40 2009] <function Foo at 0x01a3dcf0> () called
In Foo called
Bytes ----------------------------------------------------------------------------------------------------
We can see that the function object outside tcfunc is the same as the function object of wrappedfunc, which is called in the func parameter of tcfunc.
Actually defined Foo function object !!!