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