【发布时间】:2023-03-08 23:27:01
【问题描述】:
我正在尝试学习 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 方法时,我如何修改 add 方法,即当我从 add.py 导入 Math 类到不同的文件中时,我如何修改它的 add 方法。
【问题讨论】:
标签: python object python-2.7 instance monkeypatching