Well, the basics are good, talk decorator, first look at this code:
defSayhi (name):return "How is you {0}, Good morning". Format (name)defDecoator (func):deffunc_wrapper (name):return "<p>{0}</p>". Format (func (name))returnFunc_wrapperhi=decoator (Sayhi)PrintHi"Allen")
Don't you think it's particularly handy when we call the Hi () method every time?
Many people will ask, why use Decoator? Consider whether it is more convenient to add a function that returns <div></div>
Okay, here's a little syntax sugar, with the @ function modifier
defDecoator (func):deffunc_wrapper (name):return "<p>{0}</p>". Format (func (name))returnFunc_wrapper@decoatordefSayhi (name):return "How is you {0}, Good morning". Format (name)PrintSayhi ("Allen")
The code is almost unchanged, but it's cleaner, cleaner, and more elegant.
More times, many people use decorator so, is not very comfortable?
classDecorate:defDecorate (self,func):defFunc_wrapper (self):return "<p>{0}</p>". Format (func (self))returnFunc_wrapperclassPerson (object): D=decorate ()def __init__(self): Self.name="Allen"self.family="Liu"@d.decoratedefGet_fullname (self):returnself.name+" "+Self.familymy_person=Person ()PrintMy_person.get_fullname ()
<p>allen liu</p>
Python Closure and function decorators 2