Sag*_*ndu 33 python python-3.x
我在运行以下代码时遇到错误:
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()
Run Code Online (Sandbox Code Playgroud)
输出是:
Traceback (most recent call last):
File "./class_init.py", line 11, in <module>
p = Person('Harry')
TypeError: this constructor takes no arguments
Run Code Online (Sandbox Code Playgroud)
有什么问题?
Seb*_*olm 51
该方法应该被命名__init__为构造函数,而不是_init_.(注意双下划线.)
如果使用单个下划线,则只需创建一个名为的方法_init_,并获取一个不带参数的默认构造函数.
unu*_*tbu 10
使用双下划线__init__.
class Person:
def __init__(self, name):
Run Code Online (Sandbox Code Playgroud)
(Python中的所有特殊方法都以双重而不是单个下划线开头和结尾.)
| 归档时间: |
|
| 查看次数: |
50626 次 |
| 最近记录: |