Ben*_*vis 5 python decorator class-method python-decorators
我有一个装饰器,我想用它来装饰类方法。在下面的示例中,@mydec 装饰器本身可以正常工作,但是在使用 help() 或 pydoc 时它不会保留函数签名。为了解决这个问题,我查看了使用 @decorator python-decorator 包:
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()
Run Code Online (Sandbox Code Playgroud)
不幸的是,这会导致以下异常:
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)
Run Code Online (Sandbox Code Playgroud)
您不再需要提供自己的包装器,只需@decorator.decorator在内部函数上使用,它需要一个额外的第一个位置参数,该函数被包装:
@decorator.decorator
def mydec(func, cls, *args, **kwargs):
# do some stuff
return func(cls, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
该decorator包不使用装饰器的闭包,而是将包装的函数作为参数传入。
演示:
>>> @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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2454 次 |
| 最近记录: |