Python在构造函数中对self的赋值不会使对象相同

hac*_*atu 4 python constructor self

我在Python中构建一个构造函数.当使用现有对象作为其输入进行调用时,应将"new"对象设置为该同一对象.这是一个10行演示:

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
Run Code Online (Sandbox Code Playgroud)

我希望对象A(a)从现有的对象构造的aa.为什么不呢?要清楚,我想A(a)引用相同的对象a,而不是副本.

Ale*_*lli 8

self与任何其他参数一样,它是函数或方法的局部变量之一.赋值给局部变量的裸名称永远不会影响该函数或方法之外的任何内容,它只是在本地重新绑定该名称.

正如一条评论正确地指出的那样,目前还不清楚你为什么不这样做

b = a
Run Code Online (Sandbox Code Playgroud)

假设你有一个合理的理由,你需要覆盖的不是__init__,而是__new__(然后采取一些预防措施__init__以避免双重初始化).这不是一个明显的过程,所以我会等你解释你究竟想要完成什么.

补充:澄清了我同意OP的需要,工厂功能(理想情况下,我建议,作为一种类方法)更好 - 更清晰__new__,哪种方法可行(毕竟它一种类方法)但是更少 - 清晰的方式.

所以,我的代码如下:

class A(object):

    @classmethod
    def make(cls, value):
        if isinstance(value, cls): return value
        return cls(value)

    def __init__(self, value):
        self.attribute = value
Run Code Online (Sandbox Code Playgroud)

现在,

a = A.make(1)
b = A.make(a)
Run Code Online (Sandbox Code Playgroud)

完成OP的愿望,多样化地传递给参数的类型A.make.