Tools, FAQ, Tutorials:
'@...' Function Decorators
What are function decorators in Python?
✍: FYIcenter.com
A function decorator is shorthand notation to replace a function with
a new version transformed by a wrapper function.
A function decorator can be specified using the following syntax:
@decorator_wrapper_function def func(): ...
Above Python code is actually equivalent to:
def old_func(): ... func = decorator_wrapper_function(func)
In other words, if a function is decorated, the call expression will call the decorated version of the function.
If multiple decorators are specified, the call expression will call the decorated of the decorated version of the function. So the following Python code:
@a
@b
@c
def f:
...
is the same as:
def f:
...
f = a(b(c(f)))
Here is the same example as the previous tutorial in the "@..." decorator format:
>>> def wrapper(dump):
... def newDump(user):
... x = dump(user)
... print("<root>")
... for item in user:
... print("<"+item+">"+str(user[item])+"</"+item+">")
... print("</root>")
... return x
... return newDump
...
>>> @wrapper
... def dump(user):
... print(user)
...
>>> guest = {"name": "Joe", "age": 25}
>>> dump(guest)
{'name': 'Joe', 'age': 25}
<root>
<name>Joe</name>
<age>25</age>
</root>
⇒ Defining and Using Class for New Data Types
2018-05-08, ∼2951🔥, 0💬
Popular Posts:
How to Instantiate Chaincode on BYFN Channel? You can follow this tutorial to Instantiate Chaincode ...
How To Create an Array with a Sequence of Integers or Characters in PHP? The quickest way to create ...
How to add images to my EPUB books Images can be added into book content using the XHTML "img" eleme...
How to use "{{...}}" Liquid Codes in "set-body" Policy Statement? The "{{...}}" Liquid Codes in "set...
How To Convert a Character to an ASCII Value? If you want to convert characters to ASCII values, you...