gpt4 book ai didi

python - 创建对象时如何修复 'object() takes no parameters'错误?

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:07 25 4
gpt4 key购买 nike

我正在尝试运行《艰难地学习 Python》一书中的程序,但它抛出了一个错误。你能帮我看看我在这里做错了什么吗?

这是我收到的错误消息:

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...']),但会失败。

要解决此问题,请编写 __init__,每边有 2 个下划线(总共 4 个):

def __init__(self, lyrics):

关于python - 创建对象时如何修复 'object() takes no parameters'错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48595007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com