的實例,我想我還沒有undertood如何定義從namedtuple子類的類:不能初始化一個子類namedtuple
from collections import namedtuple
PD = namedtuple('PD', 'x y z')
p1 = PD(0, 'u', 1)
print p1.x #<== this works
class PDsub(PD):
__slots__ =()
def __new__(cls, x, y, z):
self = super(PDsub, cls).__new__(cls, x, y, z)
return self
def __init__(self, a):
self.x, self.y, self.z = a, a, a
def __str__(self):
return 'Foo'
p2 = PDsub(5) #<== this does not work
此代碼引發TypeError : __new__() takes exactly 4 arguments (2 given)
。
任何想法爲什麼?
__new__被__init__其被期待多個參數之前調用。 new和init需要有完全相同數量的參數。 – karthikr