学习Python的艰难之路ex40,不懂Study Drill 2

时间:2013-09-10 05:03:08

标签: python python-2.7

http://learnpythonthehardway.org/book/ex40.html

  

将歌词放在单独的变量中,然后将该变量传递给要使用的类。

我不明白怎么做,我甚至不完全确定他的意思。他是否意味着在类中定义变量?

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 sued",
                   "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()

3 个答案:

答案 0 :(得分:1)

我只是认为他的意思是做

之类的事情
 lyricsImagine = ["Imagine there's no countries","It isn't hard to do","Nothing to kill or die for"]
 songImagine = Song(lyricsImagine)
 songImagine.sing_me_a_song()

答案 1 :(得分:1)

我认为他的意思是你应该这样做:

foo = Song(happy_bday.lyrics)
foo.sing_me_a_song()

重要的是.lyrics,如果你不包含它,那么它会给你一个TypeError

答案 2 :(得分:-1)

class Song(object):

    def __init__(self):
        self.lyrics =(["Happy birthday to you",
                       "I don' want to get sued",
                       "So I'll stop right there",
                       "They rally around the family",
                       "With pockets full of shells"])

    def sing_me_a_song(self):
        for line in self.lyrics:
            print line 

happy_bday = Song()

happy_bday.sing_me_a_song()