The decorator is called at the time of import , Or execute when loading , The following code :
register = []
def regester(func):
print 'running regisster ({0})'.format(func)
register.append(func)
return func
@regester
def f1():
print "running f1()"
@regester
def f2():
print "running f2()"
def f3():
print "running f3()"
def main():
print "running main()"
print register
f1()
f2()
f3()
The results are as follows :
running regisster (<function f1 at 0x1035ae5f0>)
running regisster (<function f2 at 0x1035ae668>)
running main()
[<function f1 at 0x1035ae5f0>, <function f2 at 0x1035ae668>]
running f1()
running f2()
running f3()
Follow the normal code execution logic to execute , So the first print out should be "running main()"
, But it actually came out on the third line , The first two lines are the contents of the decorator , use Debug Mode to run , You can see it clearly .
As shown in the figure , I hit an endpoint when I first met it ,Debug After the mode runs , The program has printed out the contents of the decorator .
—— The above comes from 《 smooth Python》
I have used this before , But there was a problem , When decorating a function in a class , Parameter errors often occur , Because the first parameter of a function in a class is always self
, The parameters are often incorrect during execution , Here is a decorator function that I have successfully implemented , Can solve this problem .
# ecoding=utf-8
# Author: Weng Yanbin | Sven_Weng
# Email : [email protected]
# Web : http://wybblog.applinzi.com
import time
import functools
def log(func):
@functools.wraps(func)
def inner_methods(*args, **kwargs):
t0 = time.time()
result = func(*args, **kwargs)
t1 = time.time()
name = func.__name__
arg_list = []
if args:
arg_list.append(', '.join([str(arg) for arg in args]))
if kwargs:
pairs = ['{0}={1}'.format(k, w) for k, w in sorted(kwargs.items())]
arg_list.append(', '.join(pairs))
print "[{0}]func_name:{1},args:({2})".format(str(t1 - t0), name, arg_list)
return result
return inner_methods
This decorator is decorated , The name of the function to be executed , Print out all time of the participating in execution .