我了解了如何通过浏览这些链接在Python中运行时替换方法.[ Link1,Link2和Link3 ].
当我替换A类的"update_private_variable"方法时,它被替换但不更新私有变量.
import types
class A:
def __init__(self):
self.__private_variable = None
self.public_variable = None
def update_private_variable(self):
self.__private_variable = "Updated in A"
def update_public_variable(self):
self.public_variable = "Updated in A"
def get_private_variable(self):
return self.__private_variable
class B:
def __init__(self):
self.__private_variable = None
self.public_variable = None
def update_private_variable(self):
self.__private_variable = "Updated in B"
def update_public_variable(self):
self.public_variable = "Updated in B"
Run Code Online (Sandbox Code Playgroud)
在没有替换的情况下调用方法:
a_instance = A()
a_instance.update_private_variable()
print(a_instance.get_private_variable())
#prints "Updated in A"
Run Code Online (Sandbox Code Playgroud)
更换后调用方法时:
a_instance = A()
a_instance.update_private_variable = types.MethodType(B.update_private_variable, a_instance) …Run Code Online (Sandbox Code Playgroud)