我已经读过可以在Python中向现有对象(即,不在类定义中)添加方法.
我知道这样做并不总是好事.但是人们怎么可能这样做呢?
如果我有类似的东西
import mynewclass
Run Code Online (Sandbox Code Playgroud)
我可以为mynewclass添加一些方法吗?像概念中的以下内容:
def newmethod(self,x):
return x + self.y
mynewclass.newmethod = newmethod
Run Code Online (Sandbox Code Playgroud)
(我使用的是CPython 2.6)
我了解了如何通过浏览这些链接在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) 我希望能够将属性http://docs.python.org/library/functions.html#property添加到对象(类的特定实例).这可能吗?
关于python中鸭子打孔/猴子修补的其他一些问题:
更新:由delnan在评论中回答