【发布时间】:2018-07-22 15:05:00
【问题描述】:
我有一个简单的装饰器my_decorator,它装饰了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'
直到这里一切正常,但我看不到函数的实际签名。
my_func?
Signature: my_func(*args, **kwargs)
Docstring: <no docstring>
File: ~/<ipython-input-2-e4c91999ef66>
Type: function
如果我用 python 的decorator.decorator 装饰我的装饰器,我可以看到我的函数的签名,但我不能拥有我定义的新属性。
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 中同时拥有这两者?
【问题讨论】:
-
你在使用decorator这个模块吗?
-
如果我们谈论的是同一个模块,这似乎不是使用 decorator.decorator 的正确方法。
标签: python python-2.7 ipython python-decorators