The essence of the adorner:
When you are using a @decorator to decorate a function func, as follows:
@decoratordef func (): Pass
The interpreter will interpret the following statement as follows:
Func=decorator (func)
The essence is to pass a function as an argument to another function and then call it.
def hello (FN): Def wrapper (): print "hello,%s"%fn.__name__ fn () print "goodbye,%s"%fn.__name__ Return wrapper@hellodef foo (): print "I am foo" >>>foo () "Hello,foo" "I am Foo" "Goodbye,foo"
Hello (foo) returns the wrapper () function, so foo actually becomes a variable of wrapper, and the subsequent foo () execution actually becomes wrapper ()
Multiple adorners:
@decorator_one @decorator_twodef func (): Pass
Equivalent to Func=decorator_one (Decorator_two (func))
Adorner with parameters:
@decorator (ARG1,ARG2) def func (): Pass
Equivalent to Func=decorator (ARG1,ARG2) (func). This means that the decorator (ARG1,ARG2) function needs to return a "real decorator".
def mydecorator (arg1,arg2): Def _mydecorator1 (func): Def _mydecorator2 (*args,**kw): Res=func (*args,** KW) return res return _MYDECORATOR2 return _mydecorator1
The _mydecorator1 returned by the above function is the true adorner. Therefore, when the adorner requires parameters, the second set of encapsulation must be used. Because adorners are loaded by the interpreter when the module is first read, their use must be limited to the overall wrapper that can be applied.
With parameters and multiple adorners:
def makehtmltag (Tag,*args,**kwds): Def real_decorator (FN): css_class= "class= ' {0} '". Format (kwds["Css_class"]) if "Css_class" in Kwds Else "" Def Wrapped (*args,**kwds): Return "<" +tag+css_class+ ">" +fn (*ARGS,**KWD s) + "</" +tag+ ">" Return warpped (*args,**kwds) return Real_decorator
@makeHtmlTag (tag= ' i ', css_class= ' italic_css ') @makeHtmlTag (tag= ' b ', css_class= ' bold_css ') def hello (): Return "Hello" World ">>>hello () <i class= ' italic_css ' ><b class= ' bold_css ' >hello world</b></i>
Class-style decorators:
Class Mydecorator (object): Def __init__ (SELF,FN): print "Inside Mydecorator--init" Self.fn=fn def __ca Ll__ (self): Self.fn () print "Inside Mydecorator--call" @mydecoratordef myfunc (): print "Inside MyFunc" > >>myfunc "Inside Mydecorator--init" "Inside MyFunc" "Inside Mydecorator--call"
Rewrite the Makehtmltag code:
adorners in Python