它看起來像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
這是完全可行的,只是使用不同的範例。 –