Python Closure and function decorators 2

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.