Decorative functions in Python

Source: Internet
Author: User

In the object-oriented (OOP) design pattern, the decorator is called the adornment mode. The Deco pattern of OOP needs to be implemented through inheritance and composition, while Python supports decorator directly from the syntax level, in addition to the decorator of OOP. Python's decorator can be implemented using functions or classes.

Decorator can enhance the function of functions, although the definition is a bit complex, but it is very flexible and convenient to use.

Write a decorator that can print out and back the log before and after the function call ‘begin call‘ ‘end call‘ .

Think again about whether you can write a @log decorator that supports both:

@logdef f(): pass

also supports:

@log(‘execute‘)def f(): pass

1 #heelo.py2 __author__='Administrator'3 ImportFunctools4 defLog (text=None):5     defde (func):6 @functools. Wraps (func)7         defFirst (*args,**kw):8             ifText:9                 Print "Begin Call", Func.__name__,'input is', TextTen             Else: One                 Print "Begin Call", Func.__name__ Ars= func (*args,**kw) -             Print 'End Call' -             returnRS the         return First -  -     returnde -  + @log () - defNow (): +     Print 'i\ ' m a boy' A  at  - Now () - PrintNow.__name__

  

Decorative functions in Python

Related Article

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.