我正在构建一些代码,所以让它在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,使其成为已更新类的实例,同时保留其以前的内部状态?目前,我不得不重新运行许多比较昂贵的代码。
发布于 2016-12-31 21:55:14
我假设您使用的是3.x,而不是2.x和“经典类”。如果是这样的话,我相信更新c.__class__可以实现您想要的效果。
>>> class C():
pass
>>> c = C()
>>> class C():
def __init__(self): self.a = 3
>>> c.__class__
<class '__main__.C'> # but actual reference is to old version
>>> id(C)
2539449946696
>>> id(c.__class__)
2539449972184
>>> c.__class__ = C
>>> id(c.__class__)
2539449946696https://stackoverflow.com/questions/41411738
复制相似问题