[英]How to fix 'object() takes no parameters' error when creating object?
我正在尝试运行《Learn Python the Hard Way》一书中的程序,但它抛出了一个错误。 你能帮我解决我在这里做错了什么吗?
这是我收到的错误消息:
Traceback (most recent call last):
File "C:\Desktop\Python-testing\My-file.py", line 11, in
<module>
"So I'll stop right there"])
TypeError: object() takes no parameters
这是 Python 代码:
class Song(object):
def _init_(self, lyrics):
self.lyrics=lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I dont want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["The rally around the family",
"with pockets ful of shales"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
在 python 中,初始化方法被命名为__init__
,而不是_init_
(两个下划线而不是一个)。 所以方法定义
def _init_(self, lyrics):
只是定义了一个普通的方法,而不是覆盖object.__init__
。 因此,当您使用参数初始化该类时, object.__init__(['Happy birthday...'])
被调用,并且失败。
要解决此问题,请在每边 2 个下划线(共 4 个)中写入__init__
:
def __init__(self, lyrics):
你的构造函数应该是def __init__
而不是def _init_
。
Python 解释器将def _init_
识别为普通函数,因此,它找不到构造函数,因此会出现“object() 不带参数”的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.