更改实例方法中的类实例 [英] Change class instance inside an instance method
问题描述
任何想法如果有办法让以下代码工作
Any idea if there is a way to make the following code to work
class Test(object):
def __init__(self, var):
self.var = var
def changeme(self):
self = Test(3)
t = Test(1)
assert t.var == 1
t.changeme()
assert t.var == 3
类似于以下可以安全地用于更复杂的对象(如django模型,热插拔实例引用的数据库条目) p>
is something like the following safe to use for more complex objects (like django models, to hot swap the db entry the instance is referring to)
class Test(object):
def __init__(self, var):
self.var = var
def changeme(self):
new_instance = Test(3)
self.__dict__ = new_instance.__dict__
t = Test(1)
assert t.var == 1
t.changeme()
assert t.var == 3
推荐答案
self = Test(3)
是重新绑定本地名称 self
,没有外部可观察的效果。
self = Test(3)
is re-binding the local name self
, with no externally observable effects.
分配 self .__ dict __
(除非你在谈论具有 __ slots __
或来自具有非平凡元类的类的实例)通常是正确的,因此 self .__ init __(3 )
重新初始化实例。但我更喜欢有一个特定的方法 self.restart(3)
其中知道它在一个已经初始化的实例上调用,需要满足这种特殊和不寻常的情况。
Assigning self.__dict__
(unless you're talking about instances with __slots__
or from classes with non-trivial metaclasses) is usually OK, and so is self.__init__(3)
to re-initialize the instance. However I'd prefer to have a specific method self.restart(3)
which knows it's being called on an already-initialized instance and does whatever's needed to cater for that specific and unusual case.
这篇关于更改实例方法中的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!