我需要一种使用猴子修补的方法/字段为实例创建“代理”的方法。
您知道有任何可能的软件包吗?
这是我非常艰难的尝试,展示了我需要的功能:
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