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