在 Python 控制台更新 class 实例

Update class instance in Python console

我正在构建一些代码,因此将它放在 Python 控制台中很方便,便于实验。除了 classes 有状态,我不确定更新 class 的现有实例的最佳方法是什么,以便我可以继续玩弄它。

比如说,我有这个 class:

class Cheese:
  def __init__(self):
    self.brand    = 'Kraft'
    self.quantity = 4

然后我创建了一个实例:

c = Cheese()

现在,我将 class 修改为:

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 使其成为更新后的 class 的实例,同时保留其先前的内部状态?目前,我必须重新运行 很多有点昂贵的代码。

我假设您使用的是 3.x,而不是 2.x 和 'classic classes'。如果是这样,我相信更新 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__)
2539449946696