Recently saw an example of a decorator, not read,
#!/usr/bin/pythonclassDecorator (object):def __init__(self,f):Print "Initial Decorator"f ()def __call__(self):Print "Call Decorator"@decoratordefFun ():Print " in the fun"Print " After"Fun ()
See the most viewed articles about Python decorators from StackOverflow, here's the URL of this article
http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/1594484#1594484
Feel write very good, I also summarize summary.
The problem is that LZ wants to write an adorner:
@makebold @makeitalic def say (): return " Hello "
There is such an output:
"<b><i>Hello</i></b>"
See the shortest reply is:
defMakebold (f):return Lambda:"<b>"+ f () +"</b>"defMakeitalic (f):return Lambda:"<i>"+ f () +"</i>"@makebold @makeitalicdefsay ():return "Hello"PrintSay ()
It's so classic,
For the first example, write the snippet code:
#de on behalf of decorator Bar, simple O (∩_∩) o~,
Def de (f):
def WR ():
Print "Before Func"
F ()
Print "After Func"
Return WR
def func ():
Print "This is the Func self"
#先运行一遍代码
Func ()
#装饰函数
De_func=de (func)
#运行装饰了之后的函数
De_func ()
#或者
#装饰函数
Func=de (func)
#运行装饰了之后的函数
Func ()
#或者
De (func) ()
Another thing to understand is that the __call__ method of a class is called when the Instance=classname () () () (also written as Instance=classname (), instance ()) is used.
Python's own decorator is:
#还可以在函数定义之前加上 @de @dedef func1 (): print "**this is func-Self" func1 ()
Understanding the above example of the beginning of the article can also be written like this
Class Decorator (object): def __init__ (self,f): print "initial decorator" F () def __call__ (self): print "Call decorator" # @decoratordef Fun (): print ' In the fun ' Fun=decorator (fun) print ' after ' fun ()
Have a careful look at the article, feeling benefited, but also when they learned the time did not listen to it.
Python Decorator Learning (decorator)