【问题标题】:What's wrong with my Python code? An example in Head First Python [duplicate]我的 Python 代码有什么问题? Head First Python 中的一个示例 [重复]
【发布时间】:2013-11-11 15:47:44
【问题描述】:

上面写着

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

【问题讨论】:

标签: python class


【解决方案1】:

那是因为你没有重载 object 类的魔法 __init__ 方法。取而代之的是,您定义了一个名为 _init_ 的新方法,它对 Python 没有特殊意义(Python 中的特殊方法应该用双下划线括起来)。

只要你的类没有重载__init__,每次实例化类时都会调用一个默认值(继承自object)。并且该默认值不带任何参数。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2018-03-09
      • 1970-01-01
      相关资源
      最近更新 更多