同时运行下面的代码我得到一个错误的错误:“这个构造函数没有参数”,在__init__
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__'落入了同样的错误 – Salam