Python Notes-Decorator supplement

Source: Internet
Author: User

This essay is a supplement to Python's notes-adorners.

When using adorners, some properties of the decorated function are lost, such as the following code:

1 #!/usr/bin/env python2 3 defDeco (func):4     defwrapper ():5         Print "Wrap Start"6 func ()7         Print "Wrap end\n"8     returnwrapper9 Ten @deco One deffoo (): A     """docstring for Foo""" -     Print "In foo ():" -  the foo () - PrintFoo.__name__ - PrintFoo.__doc__

The output is as follows:

$ python decorator_test.pywrap startin foo (): Wrap Endwrappernone

It can be found that the __name__ property is wrapper, and the __doc__ attribute is none. This can be inconvenient for the usual use, and it is not always possible to rewrite __name__ and __doc__ for each function that uses adorners.

Python's Functools provides update_wrapper and wraps that can solve this problem effectively. However, Update_wrapper is called in the form of a method, while wraps encapsulates the update_wrapper with an adorner. The sample code is as follows:

1 #!/usr/bin/env python2  fromFunctoolsImportUpdate_wrapper3 4 defDeco (func):5     defwrapper ():6         Print "Wrap Start"7 func ()8         Print "Wrap end\n"9     returnUpdate_wrapper (Wrapper,func)#calling the Update_wrapper methodTen  One @deco A deffoo (): -     """docstring for Foo""" -     Print "In foo ():" the  - foo () - PrintFoo.__name__ - PrintFoo.__doc__
1 #!/usr/bin/env python2  fromFunctoolsImportWraps3 4 defDeco (func):5@wraps (func)#using adorners to implement6     defwrapper ():7         Print "Wrap Start"8 func ()9         Print "Wrap end\n"Ten     returnwrapper One  A @deco - deffoo (): -     """docstring for Foo""" the     Print "In foo ():" -  - foo () - PrintFoo.__name__ + PrintFoo.__doc__

The Foo method, now decorated by Deco, preserves the previous __name__ and __doc__ properties.

for for Foo 

Python Notes-Decorator supplement

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.