【发布时间】:2025-12-10 02:25:02
【问题描述】:
运行以下代码时出现错误:
class Person:
def _init_(self, name):
self.name = name
def hello(self):
print 'Initialising the object with its name ', self.name
p = Person('Constructor')
p.hello()
输出是:
Traceback (most recent call last):
File "./class_init.py", line 11, in <module>
p = Person('Harry')
TypeError: this constructor takes no arguments
有什么问题?
【问题讨论】:
-
答案指出
__init__使用双下划线。但是您收到错误消息的原因是默认情况下,您的类提供了一个从object继承的空__init__(self)方法。由于您没有覆盖该方法,因此它是被调用的方法。 -
在类似的拼写错误情况下(在这种情况下是一个下划线而不是两个下划线)我通过将方法命名为
__ini__陷入了同样的错误
标签: python python-3.x