Python assignment to self in constructor does not make object the same

后端 未结 4 909
日久生厌
日久生厌 2020-12-18 09:58

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 demonstratio

4条回答
  •  情深已故
    2020-12-18 10:17

    The only way to make it work exactly as you have it is to implement __new__, the constructor, rather than __init__, the initialiser (the behaviour can get rather complex if both are implemented). It would also be wise to implement __eq__ for equality comparison, although this will fall back to identity comparison. For example:

    >>> class A(object):
        def __new__(cls, value):
            if isinstance(value, cls):
                return value
            inst = super(A, cls).__new__(cls)
            inst.attribute = value
            return inst
        def __eq__(self, other):
            return self.attribute == other.attribute
    
    
    >>> a = A(1)
    >>> b = A(a)
    >>> a is b
    True
    >>> a == b
    True
    >>> a == A(1)
    True  # also equal to other instance with same attribute value
    

    You should have a look at the data model documentation, which explains the various "magic methods" available and what they do. See e.g. __new__.

提交回复
热议问题