[英]Python monkey patching objects not working as expected
我正在尝试学习python猴子补丁。 我有一个简单的示例,其中我尝试仅对单个实例而不是类本身进行猴子修补。
我的代码:
# add.py
import types
class Math(object):
def __init__(self):
self.name = ''
def add(self, x, y, name):
self.name = name
print 'calling from ', self.name
return x + y
def monkey_patch(self):
add = self.add
def squared_sum(x, y):
return x**2 + y**2
add = types.MethodType(squared_sum, self)
if __name__ == '__main__':
math = Math()
print math.add(3, 4, 'before monkey_patching')
math.monkey_patch()
print math.add(3, 4, 'after monkey_patching')
预期产量:
calling from before monkey_patching
7
calling from after monkey_patching
25
产生的输出:
calling from before monkey_patching
7
calling from after monkey_patching
7
有人可以指出我要去哪里了。 而且,当我从其他文件执行添加方法时,如何猴子修补方法,即当我从其他文件中的add.py导入Math类时,如何猴子修补了它的add方法。
您的代码没有执行您认为的操作:
def monkey_patch(self):
add = self.add # add now points to self.add
def squared_sum(x, y):
return x**2 + y**2
add = types.MethodType(squared_sum, self) # add now points to squared_sum
# method ends, add and squared_sum are abandoned
这实际上并没有改变 self.add
。 另外, squared_sum
不使用self
或name
参数,这与add
不同,并且不具有add
执行的print
。 为使此工作充分进行,请执行以下操作:
def monkey_patch(self):
def squared_sum(self, x, y, name):
self.name = name
print 'calling from ', self.name
return x**2 + y**2
self.add = types.MethodType(squared_sum, self)
要在类定义之外打补丁:
math = Math()
def func(self, x, y, name):
return x ** y
math.add = types.MethodType(func, math)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.