马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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 don't want to get used.",
"So I'll stop right there"])
bulls_on_parade=Song(["They rally around the family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
想知道为什么这里显示name 'Song' is not defined呢,如果想让我的代码跑起来应该怎么修改呢
你的代码出现问题主要是有两个原因。
1. Python的初始化函数应该是 __init__ 而不是 _init_ 。你的初始化函数缺少一个下划线。
2. 创建类对象和调用类方法应该在类定义之外进行,而不是在类定义的内部。
所以,你应该将你的代码修改为以下形式:
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 don't want to get used.",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
这样就应该能解决你的问题。如果有其他问题,欢迎随时向我提问。
|