小能豆

创建对象时如何修复“object() 不接受参数”错误?

py

这是我收到的错误消息:

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()

阅读 24

收藏
2024-11-05

共1个答案

小能豆

你的代码中出现了一个小错误,导致了 TypeError。具体来说,__init__ 方法的名称拼写错误,应该是 __init__(双下划线)而不是 _init_(单下划线)。

下面是修正后的代码:

class Song(object):
    def __init__(self, lyrics):  # 修正为 __init__
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)  # 使用 print() 函数,以支持 Python 3.x

# 创建实例
happy_bday = Song([
    "Happy birthday to you",
    "I don't want to get sued",
    "So I'll stop right there"
])

bulls_on_parade = Song([
    "Rally around the family",
    "With pockets full of shells"
])

# 调用方法
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()

修正说明

  1. __init__ 方法拼写:确保构造函数命名为 __init__,这对于初始化类实例非常重要。
  2. 打印语句:在 Python 3.x 中,使用 print() 函数来打印,而不是 Python 2.x 的语法。

运行结果

修正后的代码应该能够正常运行并打印出你所定义的歌词。尝试运行它,你将看到每首歌的歌词被打印到控制台。

2024-11-05