在Python控制台中更新类实例

时间:2016-12-31 21:08:45

标签: python-3.x class monkeypatching

我正在构建一些代码,因此将它放在Python控制台中以方便实验非常方便。 ' cept表示类具有状态,我不确定更新类的现有实例的最佳方法是什么,以便我可以继续使用它。

比如说,我有这个课:

.layout {
  ...
  overflow: hidden;
}

我创建了一个实例:

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

1 个答案:

答案 0 :(得分:1)

我假设你使用的是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__)
2539449946696