0

モンキー パッチを適用したメソッド/フィールドを使用して、インスタンスへの「プロキシ」を作成する方法が必要です。

  • コンテキスト マネージャーを使用したり、インスタンスを直接変更したりしたくありません。
  • 継承を使用できません。インスタンスが与えられているだけです。

それを可能にするパッケージを知っていますか?

必要な機能を示す非常に大まかな試みは次のとおりです。

class Foo:
    def __init__(self):
        print('Foo init')

    def m1(self):
        print("Foo - m1")
        self.m2()

    def m2(self):
        print("Foo - m2")
        self.m3()

    # I want to alter the behavior of this method in a single (isolated) instance!
    def m3(self):
        print("Foo - m3")


class MyPatchingProxy:
    def __init__(self, wrapped):
        self.wrapped = wrapped

    def __getattr__(self, item):
        try:
            return getattr(self.wrapped.__class__, item).__get__(self, self.__class__) # something with a descriptor
        except AttributeError:
            return getattr(self.wrapped, item) # something else

    def m3(self, *args, **kwargs):
        print("Wrapped M3. Now comes the original...")
        self.wrapped.m3(*args, **kwargs)
        print("... and the wrapper continues.")



my_foo = Foo()
# Foo init
my_foo.m1()
# Foo - m1
# Foo - m2
# Foo - m3

print('-'*80)

wrapped_foo = MyPatchingProxy(my_foo)
wrapped_foo.m1()
# Foo - m1
# Foo - m2
# Wrapped M3. Now comes the original...
# Foo - m3
# ... and the wrapper continues.

print('-'*80)

print("And the original my_foo works as before")
my_foo.m1()
# Foo - m1
# Foo - m2
# Foo - m3
4

0 に答える 0