It looks like this or this are somewhat related threads, but still haven't figured things out :)
I'm trying to create a subclass of namedtuple
and provide different initializers so that I can construct objects in different ways. For example:
>>> from collections import namedtuple
>>> class C(namedtuple("C", "x, y")) :
... __slots__ = ()
... def __init__(self, obj) : # Initialize a C instance by copying values from obj
... self.x = obj.a
... self.y = obj.b
... def __init__(self, x, y) : # Initialize a C instance from the parameters
... self.x = x
... self.y = y
However, that doesn't work:
>>> c = C(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in __init__
AttributeError: can't set attribute
After some poking around (for example, see this thread) I tried to use constructors instead of initializers:
>>> from collections import namedtuple
>>> class C(namedtuple("C", "x, y")) :
... __slots__ = ()
... def __new__(cls, obj) :
... self = super(C, cls).__new__(cls, obj.a, obj.b)
... def __new__(cls, x, y) :
... self = super(C, cls).__new__(cls, x, y)
which seemed to construct an object but then I can't read its attributes:
>>> c = C(1,2)
>>> c.x, c.y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'x'
Where am I going wrong here? How can I create a subclass with multiple constructors or initializers?
__init__
and__new__
methods? Only the second one counts, it overwrites the first. Python does not 'overload' method signatures. – Calculusx
or anobj
, and the second parameter would be eithery
orNone
as a default value. I'll noodle on that, see what I like better. – Interclavicle