This article mainly uses the Python decorator for an example to introduce the Python decorator in detail. it is very practical. if you need it, you can refer to it. Today, I want to use the python decorator for an operation. the code is as follows:
>>> def mu(x): def _mu(*args,**kwargs): return x*x return _mu>>> @mudef test(x,y): print '%s,%s' %(x,y)>>> test(3,5)Traceback (most recent call last): File "
", line 1, in
test(3,5) File "
", line 3, in _mu return x*xTypeError: unsupported operand type(s) for *: 'function' and 'function'
It turns out that functions and functions cannot be computed in this way!
What should we do?
In [1]: from functools import wrapsIn [2]: def mu(x): ...: @wraps(x) ...: def _mu(*args,**kwargs): ...: x,y=args ...: return x*x ...: return _mu ...: In [3]: @mu ...: def test(x,y): ...: print '%s,%s' %(x,y) ...: In [4]: test(3,4)Out[4]: 9
When implementing the Python decorator, you need to pay attention to some details. For example, the decorated function is actually another function (function attributes such as the function name will change)
The Python functools package provides a decorator called wraps to eliminate such side effects. When writing a decorator, it is best to add the functools wrap before implementation, which can retain the name of the original function and docstring.
The above is all the content of this article. I hope you will like it.