【问题标题】:Update class instance in Python console在 Python 控制台中更新类实例
【发布时间】: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


    【解决方案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
    

    【讨论】:

    • 这能回答你的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2013-12-27
    • 2023-04-08
    • 1970-01-01
    • 2019-05-07
    • 2012-03-29
    • 1970-01-01
    相关资源
    最近更新 更多