I. Contains a decorator
#encoding: utf-8 ############ contains a decorator ######### def outer(func): def inner(*args, **kwargs):# To decorate f1 (), here with these two formal parameters, can accept any parameter, regardless of f1 defined a few parameters print "1" r = func(*args, **kwargs)# Use func here, not f1. print "2" return r return inner @outer # Don't put parentheses around this outer def f1(a1, a2): print "a1 + a2 = " return a1 + a2 f1(1,2)
II. Contains two (more) decorators
############ contains two decorators ######### def outer0(func):#First def inner(*args, **kwargs): print "AAAAAAAAA" r = func(*args, **kwargs) print "BBBBBBBB" return r return inner def outer(func): #The second one # def inner(*args, **kwargs):# To decorate f1 (), here with these two formal parameters, can accept any parameter, regardless of f1 defined a few parameters print "1" r = func(*args, **kwargs)# Use func here, not f1. print "2" return r return inner @outer0 # two decorators, the process is: the execution of f1(), first execute (), ().func call outer's inner function, that is, the () function as the argument to outer0. # Then ().func then calls f1() @outer # Don't put parentheses around this outer def f1(a1, a2): print "a1 + a2 = %d" %(a1+a2) return 1 f1(1,2)
The above this python decorator primer (recommended) is all I have to share with you, I hope to give you a reference, and I hope you support me more.