我想修补一个单一的类方法,保留旧的功能。考虑一下我的代码来获取想法。这是我的代码(非常合成的例子)。
#!/usr/bin/env python
class A:
@classmethod
def foo(kls, param):
print 'A.foo called, param is ' + param
def bar(self, param):
print 'A.bar called, param is ' + param
a = A()
a.foo('param_foo')
a.bar('param_bar')
# Patching things
def bar_wrapper(wrapped_func):
def _w(*args, **kwargs):
print '<bar_wrap>'
wrapped_func(*args, **kwargs)
print '</bar_wrap>'
return _w
def foo_wrapper(wrapped_func):
# Something missing here?
def _w(*args, **kwargs):
print '<foo_wrap>'
wrapped_func(*args, **kwargs)
print '</foo_wrap>'
return _w
# Everything is pretty ok
A.bar = bar_wrapper(A.bar)
a.bar('is_is_wrapped?')
# Failed to wrap @classmethod
A.foo = foo_wrapper(A.foo)
A.foo('another_wrap_test')
这是我期望输出的内容:
A.foo called, param is param_foo
A.bar called, param is param_bar
<bar_wrap>
A.bar called, param is is_is_wrapped?
</bar_wrap>
<foo_wrap>
A.foo called, param is another_wrap_test
</foo_wrap>
这就是我得到的:
A.foo called, param is param_foo
A.bar called, param is param_bar
<bar_wrap>
A.bar called, param is is_is_wrapped?
</bar_wrap>
Traceback (most recent call last):
File "./pytest.py", line 39, in <module>
A.foo('another_wrap_test')
TypeError: unbound method _w() must be called with A instance as first argument (got str instance instead)
似乎在包装过程中丢失了一个参数(class-param)。或者我只是不想装饰功能?
提前致谢。
答案 0 :(得分:8)
当您访问某个类的方法时,它会被包裹;方法在这里充当descriptors。
您可能想要再次打开该方法,返回一个包装的包装器:
def foo_wrapper(wrapped_func):
wrapped_func = wrapped_func.__func__
def _w(*args, **kwargs):
print '<foo_wrap>'
wrapped_func(*args, **kwargs)
print '</foo_wrap>'
return classmethod(_w)
现在返回的装饰器本身就是一个类方法,包装起作用:
>>> class A:
... @classmethod
... def foo(kls, param):
... print 'A.foo called, param is ' + param
...
>>> def foo_wrapper(wrapped_func):
... wrapped_func = wrapped_func.__func__
... def _w(*args, **kwargs):
... print '<foo_wrap>'
... wrapped_func(*args, **kwargs)
... print '</foo_wrap>'
... return classmethod(_w)
...
>>> A.foo = foo_wrapper(A.foo)
>>> A.foo('bar')
<foo_wrap>
A.foo called, param is bar
</foo_wrap>