如何修复Python cod中的object()不带参数错误

2024-04-20 09:37:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图运行的程序从书中学习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()

Tags: inselfrightsoobjectsong错误line
2条回答

你的构造函数应该是def\u init\u,而不是def\u init\u。 Python解释器将def\u init\识别为一个普通函数,因此它找不到构造函数,从而导致object()不带参数的错误。你知道吗

在python中,初始值设定项方法的名称是__init__,而不是_init_(用两个下划线代替一个下划线)。所以方法定义

def _init_(self, lyrics):

只定义一个普通方法,而不是重写object.__init__。因此,当您使用参数初始化类时,object.__init__(['Happy birthday...'])被调用,并且失败。你知道吗

要解决此问题,请在__init__两边各写2个下划线(总共4个):

def __init__(self, lyrics):

相关问题 更多 >