这是我收到的错误消息:
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()
你的代码中出现了一个小错误,导致了 TypeError。具体来说,__init__ 方法的名称拼写错误,应该是 __init__(双下划线)而不是 _init_(单下划线)。
TypeError
__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()
print()
修正后的代码应该能够正常运行并打印出你所定义的歌词。尝试运行它,你将看到每首歌的歌词被打印到控制台。