Python在构造函数中的赋值不会使对象相同 [英] Python assignment to self in constructor does not make object the same
问题描述
我在Python中构造一个构造函数。当使用现有对象作为其输入时,它应该将新对象设置为同一对象。这里是一个10行演示:
A类:
def __init __(self,value):
如果isinstance(value,A):
self = value
else:
self.attribute = value
a = A(1)
b = A和b应该引用同一个对象
print(b是a,b是a)#this应该是true:identity应该是相同的
print(b == a b == a)#this应该为true:值应该是相同的
A(a)
从现有对象构造为
a
。为什么不是?要清楚,我想要 A(a)
引用与 a
相同的对象,而不是副本。与任何其他参数一样,p>
self
功能或方法。对局部变量的裸名赋值不会影响该函数或方法之外的任何东西,它只是在本地重新绑定该名称。
正如一个注释所暗示的,为什么你不会只是做
b = a
假设你有一个合理的理由,你需要重写的不是 __ init __
,而是 __ new__
(然后在 __ init __
中采取一些预防措施,以避免双重初始化)。这不是一个明显的课程,所以我会等待你解释你正在完成什么。
补充:澄清了我同意OP的需求一个工厂函数(理想情况下,我建议,作为一个类方法)比 __ new __
更好 - 更清楚,这将工作( 类方法)。
所以,我将代码如下:
class A(object):
/ pre>
@classmethod
def make(cls,value):
if isinstance ):返回值
return cls(value)
def __init __(self,value):
self.attribute = value
现在,
a = A.make )
b = A.make(a)
完成OP的愿望,的参数传递给
A.make
。I am making a constructor in Python. When called with an existing object as its input, it should set the "new" object to that same object. Here is a 10 line demonstration:
class A: def __init__(self, value): if isinstance(value, A): self = value else: self.attribute = value a = A(1) b = A(a)#a and b should be references to the same object print("b is a", b is a)#this should be true: the identities should be the same print("b == a", b == a)#this should be true: the values should be the same
I want the object
A(a)
constructed from the existing objecta
to bea
. Why is it not? To be clear, I wantA(a)
to reference the same object asa
, NOT a copy.解决方案
self
, like any other argument, is among the local variables of a function or method. Assignment to the bare name of a local variable never affects anything outside of that function or method, it just locally rebinds that name.As a comment rightly suggests, it's unclear why you wouldn't just do
b = a
Assuming you have a sound reason, what you need to override is not
__init__
, but rather__new__
(then take some precaution in__init__
to avoid double initialization). It's not an obvious course so I'll wait for you to explain what exactly you're trying to accomplish.Added: having clarified the need I agree with the OP that a factory function (ideally, I suggest, as a class method) is better -- and clearer than
__new__
, which would work (it is a class method after all) but in a less-sharply-clear way.So, I would code as follows:
class A(object): @classmethod def make(cls, value): if isinstance(value, cls): return value return cls(value) def __init__(self, value): self.attribute = value
Now,
a = A.make(1) b = A.make(a)
accomplishes the OP's desires, polymorphically over the type of argument passed to
A.make
.这篇关于Python在构造函数中的赋值不会使对象相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!