既存のオブジェクトメソッドにデコレータを追加するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/1420484

  •  07-07-2019
  •  | 
  •  

質問

モジュール/クラスを使用している場合、制御できない場合、メソッドの1つをどのようにデコレートしますか?

私は次のことができることを理解しています: my_decorate_method(target_method)()

それも可能ですか?

役に立ちましたか?

解決

はい、可能ですが、いくつかの問題があります。 まず、クラスからメソッドを取得するには、関数自体ではなくワーパーオブジェクトを取得します。

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

他のヒント

これをしないでください。

継承を使用します。

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.

今、メインプログラムを修正して、 some_module.AClass の代わりに MyVersionOfAClass を使用します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top