带有猴子修补实例方法的Python复制对象

问题描述

在猴子修补实例方法(使用types.MethodType)之后,我将猴子修补对象传递到库(使用copy.copy复制该对象并调用猴子修补方法。猴子修补方法成功调用,但是self参数引用了旧的(未复制的对象)。

import copy
import types


class Person:
    def __init__(self,lang):
        self.lang = lang

    def hello(self,n):
        print(id(self),f"{n} times hello in {self.lang}")


def mean_hello(self,n):
    print(id(self),f"{n} times mean hello in {self.lang}")


a = Person('English')
b = copy.copy(a)
b.lang = "French"
print(id(a),id(b))  # 139885310130440 139885310130720
a.hello(1)  # 139885310130440 1 times hello in English
b.hello(1)  # 139885310130720 1 times hello in French

a.hello = types.MethodType(mean_hello,a)
c = copy.copy(a)
c.lang = 'German'
print(id(a),id(c))  # 139885310130440 139885310130664
a.hello(2)  # 139885310130440 2 times mean hello in English
c.hello(2)  # 139885310130440 2 times mean hello in English

从示例中可以看出,最后一行c.hello(2)调用猴子补丁方法,其中self引用了a。为什么会这样?有办法避免这种情况吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)