它看起来像this或this有些相关的线程,但仍然没有想通的事情了:)无法为namedtuple的子类设置属性
我试图创建的namedtuple
一个子类,并提供不同的初始化器,以便我可以用不同的方式构建对象。例如:
>>> 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
然而,这并不工作:
>>> 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
经过一番打探(例如,见this线程)我试图用构造函数,而不是初始化:
>>> 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)
它似乎构造一个对象,但我不能读取其属性:
>>> 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'
我在哪里错了?我如何创建一个具有多个构造函数或初始化函数的子类?
为什么你有双'__init__'和'__new__'方法?只有第二个是重要的,它会覆盖第一个。 Python不会“重载”方法签名。 –
没有重载...所以这意味着我以不同方式创建C实例的初始目标(取决于重载的构造函数)实际上不可行? – Jens
这是完全可行的,只是使用不同的范例。 –