【问题标题】:How can I add a decorator to an existing object method?如何将装饰器添加到现有对象方法?
【发布时间】:2010-11-28 01:47:56
【问题描述】:

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

我知道我可以:my_decorate_method(target_method)(),但我希望在调用 target_method 的任何地方都能发生这种情况,而无需进行搜索/替换。

有可能吗?

【问题讨论】:

    标签: python decorator


    【解决方案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.
    

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

    【讨论】:

    • 这是我看待问题的原始方式,但工作量很大。接受答案中的方法很有用 - 即使它不是最正确的做事方式。
    • 这不是“更正确”的问题,而是“可读”和“可维护”的问题。您的用例正是 OO 语言具有继承性的确切原因。它可能看起来像很多工作,但这是每个其他程序员都希望看到的。从长远来看,有趣的动态装饰器是一种负担。普通的旧继承不会成为负担。
    【解决方案2】:

    是的,这是可能的,但有几个问题。 首先,你从类中获取方法,显然你得到的是一个变形对象,而不是函数本身。

    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)
    

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

    x = X()
    x.m(1)         #>>> 1
    X.m = increase_decorator( vars(X)['m'] )
    x.m(1)         #>>> 2
    

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2016-08-29
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多