它说
sarah = Athlete('Sarah Sweeney', '2002-6-17', ['2:58', '2.58', '1.56'])
TypeError: object() takes no parameters
怎么了?谢谢。这是Head First Python的例子
class Athlete:
def _init_(self, a_name, a_dob=None, a_times=[]):
self.name = a_name
self.dob = a_dob
self.times = a_times
sarah = Athlete('Sarah Sweeney', '2002-6-17', ['2:58', '2.58', '1.56'])
答案 0 :(得分:4)
那是因为你没有超载__init__
类的魔法object
方法。而不是你定义一个名为_init_
的新方法,它对Python没有特殊意义(Python中的特殊方法应该用双下划线包围)。
只要您的类不重载__init__
,每次实例化类时都会调用默认值(继承自object
)。而那个默认的不带参数。
另请参阅:Special (magic) methods in Python,Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...)
答案 1 :(得分:3)
你拼错了__init__
(请注意双在开头和结尾的下划线。)