我的Python代码出了什么问题? Head First Python中的一个例子

时间:2013-11-11 15:47:44

标签: python class

它说

    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'])

2 个答案:

答案 0 :(得分:4)

那是因为你没有超载__init__类的魔法object方法。而不是你定义一个名为_init_的新方法,它对Python没有特殊意义(Python中的特殊方法应该用双下划线包围)。

只要您的类不重载__init__,每次实例化类时都会调用默认值(继承自object)。而那个默认的不带参数。

另请参阅:Special (magic) methods in PythonWhere is the Python documentation for the special methods? (__init__, __new__, __len__, ...)

答案 1 :(得分:3)

你拼错了__init__(请注意在开头和结尾的下划线。)