python – 如何包装(猴子补丁)@classmethod
作者:互联网
我想修补一个单一的类方法,保持旧的功能.考虑一下我的代码来获取想法.这是我的代码(非常合成的例子).
#!/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).或者我只是没有装饰功能的想法?
提前致谢.
解决方法:
当你访问一个类的方法时,它就被包裹了;方法在这里充当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>
标签:python,decorator,class-method,monkeypatching,python-decorators 来源: https://codeday.me/bug/20190612/1227131.html