Python 如何向现有对象方法添加装饰器?
如果我正在使用一个我无法控制的模块/类,我将如何装饰其中一个方法 我知道我可以:Python 如何向现有对象方法添加装饰器?,python,decorator,Python,Decorator,如果我正在使用一个我无法控制的模块/类,我将如何装饰其中一个方法 我知道我可以:my\u-decoration\u-method(target\u-method)(),但我希望在调用target\u-method的任何地方都能做到这一点,而无需进行搜索/替换 甚至有可能吗?是的,有可能,但有几个问题。 首先,当你们从类中得到方法时,你们得到的是一个warper对象,而不是函数本身 class X(object): def m(self,x): print x print
my\u-decoration\u-method(target\u-method)(
),但我希望在调用target\u-method
的任何地方都能做到这一点,而无需进行搜索/替换
甚至有可能吗?是的,有可能,但有几个问题。 首先,当你们从类中得到方法时,你们得到的是一个warper对象,而不是函数本身
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)
不要这样做
使用继承
import some_module
class MyVersionOfAClass( some_module.AClass ):
def someMethod( self, *args, **kwargs ):
# do your "decoration" here.
super( MyVersionOfAClass, self ). someMethod( *args, **kwargs )
# you can also do "decoration" here.
现在,修复主程序以使用
myversionofclass
而不是some_module.AClass
这是我最初看待问题的方式,但需要做大量工作。知道公认答案中的方法是很有用的,即使它不是做事情的最正确的方法。这不是“更正确”的问题,而是“可读性”和“可维护性”的问题。您的用例正是OO语言具有继承性的原因。这看起来可能需要做很多工作,但这是每个其他程序员都希望看到的。从长远来看,有趣的动态装饰是一种负担。普通的旧遗产不会成为一种负担。
import some_module
class MyVersionOfAClass( some_module.AClass ):
def someMethod( self, *args, **kwargs ):
# do your "decoration" here.
super( MyVersionOfAClass, self ). someMethod( *args, **kwargs )
# you can also do "decoration" here.