调用构造函数时如何解决'object()不带参数'错误?

问题描述 投票:1回答:2

我正在尝试从“学习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
2个回答
3
投票

在python中,初始化方法的名称为__init__,而不是_init_(两个下划线一个)。所以方法定义

def _init_(self, lyrics):

仅定义一个普通方法,而不是覆盖object.__init__。因此,当您使用参数初始化类时,会调用object.__init__(['Happy birthday...']),但失败。

要解决此问题,请在__init__的每侧写上两个下划线(总共4个):

def __init__(self, lyrics):

1
投票

您的构造函数应为def __init__而不是def _init_。Python解释器将def _init_识别为普通函数,因此无法找到构造函数,因此object()不接受参数的错误。

© www.soinside.com 2019 - 2024. All rights reserved.