如何将装饰器添加到现有对象方法?

Phi*_*ham 8 python decorator

如果我使用模块/类我无法控制,我将如何装饰其中一个方法?

我明白我可以:my_decorate_method(target_method)()但是我希望无论在哪里target_method调用都可以实现这一点,而无需进行搜索/替换.

它甚至可能吗?

S.L*_*ott 8

不要这样做.

使用继承.

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.
Run Code Online (Sandbox Code Playgroud)

现在,修复您使用的主程序MyVersionOfAClass而不是some_module.AClass.


Arp*_*ius 3

是的,这是可能的,但有几个问题。首先,当你以明显的方式从类中获取方法时,你会得到一个扭曲对象,但不是函数本身。

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)
Run Code Online (Sandbox Code Playgroud)

其次我不知道设置新方法是否始终有效:

x = X()
x.m(1)         #>>> 1
X.m = increase_decorator( vars(X)['m'] )
x.m(1)         #>>> 2
Run Code Online (Sandbox Code Playgroud)