如何将装饰器添加到现有的对象方法? [英] How can I add a decorator to an existing object method?
本文介绍了如何将装饰器添加到现有的对象方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我使用无法控制的模块/类,该如何装饰其中一种方法?
If I'm using a module/class I have no control over, how would I decorate one of the methods?
我知道我可以: my_decorate_method(target_method)()
但我希望无论在何处发生这种情况<无需执行搜索/替换即可调用code> target_method 。
I understand I can: my_decorate_method(target_method)()
but I'm looking to have this happen wherever target_method
is called without having to do a search/replace.
是否有可能?
推荐答案
是可以的,但是有几个问题。
首先,您会以明显的方式从类中获取方法,而不是函数本身。
Yes it's possible, but there are several problems. First whet you get method from class in obvious way you get a warper object but not the function itself.
class X(object):
def m(self,x):
print x
print X.m #>>> <unbound method X.m>
print vars(X)['m'] #>>> <function m at 0x9e17e64>
def increase_decorator(function):
return lambda self,x: function(self,x+1)
第二个,我不知道设置新方法是否始终有效:
Second I don't know if settings new method will always work:
x = X()
x.m(1) #>>> 1
X.m = increase_decorator( vars(X)['m'] )
x.m(1) #>>> 2
这篇关于如何将装饰器添加到现有的对象方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文