更改实例方法内的类实例
任何想法是否有办法使以下代码工作
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 模型,热交换实例所引用的数据库条目)
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
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
self = Test(3)
正在重新绑定本地名称self
,没有外部可观察到的影响。分配
self.__dict__
(除非您正在谈论带有__slots__
的实例或具有重要元类的类)通常是可以的,self.__init__ 也是如此。 (3)
重新初始化实例。不过,我更喜欢有一个特定的方法self.restart(3)
,它知道它正在一个已经初始化的实例上调用,并执行满足该特定需求所需的任何操作和不寻常的情况。self = Test(3)
is re-binding the local nameself
, with no externally observable effects.Assigning
self.__dict__
(unless you're talking about instances with__slots__
or from classes with non-trivial metaclasses) is usually OK, and so isself.__init__(3)
to re-initialize the instance. However I'd prefer to have a specific methodself.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.不,也不。
话虽如此,您可以更改类,但也不要这样做。
No, and no.
Having said that, you can change the class, but don't do that either.
前面的代码可以工作,但它不会做太多事情,因为它只是替换了changeme()范围内名为“self”的对象。 Python 名称并不锁定于值,它们始终与其范围或命名空间相关。
要执行您想要的操作,您需要访问类外部的名称,您可以从类内部分配该名称:
这基本上只是覆盖名称“myclass”以指向新实例。它不会像您想象的那样“覆盖”第一个实例。旧实例仍然存在,并且将被垃圾收集,除非在其他地方引用。
The former code works, except it won't do much, seeing as it just replaces the object named 'self' within the scope of changeme(). Python names aren't locked to values, they are always relative to their scope or namespace.
To do what you want you'd need to have access to a name outside the class, which you could assign to from within it:
This basically just overwrites the name 'myclass' to point to the new instance. It doesn't "overwrite" the first instance like you might think. The old instance still lives, and will be garbage collected unless referenced elsewhere.