本文介绍了Python装饰器保持签名和用户定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我的简单装饰 my_decorator
,它装饰 my_func
。
I have my simple decorator my_decorator
which decorates the my_func
.
def my_decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper._decorator_name_ = 'my_decorator'
return wrapper
@my_decorator
def my_func(x):
print('hello %s'%x)
my_func._decorator_name_
'my_decorator'
到此为止工作,但我看不到该功能的实际签名。
Till here things work, but I can't see the actual signature of the function.
my_func?
Signature: my_func(*args, **kwargs)
Docstring: <no docstring>
File: ~/<ipython-input-2-e4c91999ef66>
Type: function
如果我用python的装饰器装饰我的装饰器.decorator
,我可以看到我的函数的签名,但我不能拥有我定义的新属性。
If I decorate my decorator with python's decorator.decorator
, I can see the signature of my function but I can't have the new property which I have defined.
import decorator
@decorator.decorator
def my_decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper._decorator_name_ = 'my_decorator'
return wrapper
@my_decorator
def my_func(x):
print('hello %s'%x)
my_func?
Signature: my_func(x)
Docstring: <no docstring>
File: ~/<ipython-input-8-934f46134434>
Type: function
my_func._decorator_name_
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-7e3ef4ebfc8b> in <module>()
----> 1 my_func._decorator_name_
AttributeError: 'function' object has no attribute '_decorator_name_'
如何在python2.7中同时使用?
How can I have both in python2.7?
推荐答案
对于Python 3,使用:
For Python 3, using functools.wraps in standard library:
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper._decorator_name_ = 'my_decorator'
return wrapper
@my_decorator
def my_func(x):
print('hello %s'%x)
print(my_func._decorator_name_)
这篇关于Python装饰器保持签名和用户定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!