“这个构造函数没有参数"__init__ 中的错误 [英] "This constructor takes no arguments" error in __init__
本文介绍了“这个构造函数没有参数"__init__ 中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在运行以下代码时遇到错误:
I'm getting an error while running the following code:
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__
为构造函数,而不是 _init_
.(注意双下划线.)
The method should be named __init__
to be a constructor, not _init_
. (Note the double underscores.)
如果您使用单下划线,您只需创建一个名为 _init_
的方法,并获得一个默认构造函数,该构造函数不接受任何参数.
If you use single underscores, you merely create a method named _init_
, and get a default constructor, which takes no arguments.
这篇关于“这个构造函数没有参数"__init__ 中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文