问题描述
我有一个装饰器,我想用它来装饰类方法。在下面的示例中,@mydec装饰器可以正常工作,但是在使用help()或pydoc时,它不会保留函数签名。为了解决这个问题,我研究了使用@decorator python-decorator软件包:
I'm have a decorator that I want to use to decorate class methods. In the following example, the @mydec decorator works fine on its own, however it does not preserve the function signature when using help() or pydoc. In order to fix this, I looked at using @decorator python-decorator package:
import functools
import decorator
@decorator.decorator
def mydec(func):
@functools.wraps(func)
def inner(cls, *args, **kwargs):
# do some stuff
return func(cls, *args, **kwargs)
return inner
class Foo(object):
@classmethod
@mydec
def bar(cls, baz='test', qux=None):
print (baz, qux)
Foo.bar()
不幸的是,这导致以下异常:
Unfortunately, this results in the following exception:
Traceback (most recent call last):
File "/tmp/test.py", line 21, in <module>
Foo.bar()
File "<string>", line 2, in bar
TypeError: mydec() takes exactly 1 argument (4 given)
推荐答案
您不再需要提供自己的包装器,只需使用 inner 函数上的> @ decorator.decorator
,它需要一个额外的第一个位置参数,该函数包装为:
You do not need to provide your own wrapper anymore, just use @decorator.decorator
on the inner function, which takes one extra first positional argument, the function wrapped:
@decorator.decorator
def mydec(func, cls, *args, **kwargs):
# do some stuff
return func(cls, *args, **kwargs)
装饰器
package不对装饰使用闭包,而是将包装函数作为参数传递。
The decorator
package doesn't use a closure for decorators and instead passes in the wrapped function as an argument.
Demo:
>>> @decorator.decorator
... def mydec(func, cls, *args, **kwargs):
... # do some stuff
... return func(cls, *args, **kwargs)
...
>>> class Foo(object):
... @classmethod
... @mydec
... def bar(cls, baz='test', qux=None):
... print (baz, qux)
...
>>> Foo.bar()
('test', None)
这篇关于如何使用python-decorator包来装饰类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!