Python 使用monkey补丁方法的实例代理
我需要一种方法来创建一个“代理”到一个带有猴子补丁的方法/字段的实例Python 使用monkey补丁方法的实例代理,python,python-3.x,instance,monkeypatching,proxy-pattern,Python,Python 3.x,Instance,Monkeypatching,Proxy Pattern,我需要一种方法来创建一个“代理”到一个带有猴子补丁的方法/字段的实例 我不想使用上下文管理器和/或直接修改实例 我不能使用继承-我有一个实例,就是这样 您知道有什么套餐可以让这成为可能吗? 下面是我的粗略尝试,展示了我需要的功能: class Foo: def __init__(self): print('Foo init') def m1(self): print("Foo - m1") self.m2() def
- 我不想使用上下文管理器和/或直接修改实例
- 我不能使用继承-我有一个实例,就是这样
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
你的代码片段对我来说很好,为什么还要麻烦使用一个包呢?这个库可能很合适:是的,我已经尝试了
wrapt
,但是我不知道如何使用这个库来实现期望的结果。我最终直接在实例中修补了该方法,而不是在代理中修补——但这不是我想要的。>为什么要费心使用包,因为有人可能已经编写了测试、调试并修复了许多关键案例。上述被剪断的部分绝不是防弹的;)我已经用wrapt
lib写了一个例子,有什么反馈吗?