【发布时间】:2017-05-15 16:04:32
【问题描述】:
我正在构建一些代码,因此可以很方便地将其放在 Python 控制台中以便于进行实验。 '除了类有状态,我不确定最好的方法是更新一个类的现有实例,以便我可以继续玩弄它。
比如说,我有这个类:
class Cheese:
def __init__(self):
self.brand = 'Kraft'
self.quantity = 4
我创建了一个实例:
c = Cheese()
现在,我像这样修改类:
class Cheese:
def __init__(self):
self.brand = 'Kraft'
self.quantity = 4
def munch():
self.quantity = self.quantity-1
#Possibly many other new methods or changes to existing methods
#Possibly incrementally updating things many times
如何更新c 使其成为更新后类的实例,同时保留其先前的内部状态?目前,我必须重新运行很多有点昂贵的代码。
【问题讨论】:
标签: python-3.x class monkeypatching