0

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

3 回答 3

1

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

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

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

于 2013-09-14T16:07:07.430 回答
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()
于 2013-09-10T06:20:55.277 回答
-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()
于 2017-07-08T02:07:48.870 回答