我正在尝试在class中学习Python,这是我为自己做的练习。我想创建一个可以定期演唱歌曲,也可以反向演唱歌曲的课程。所以这是我输入的内容:

class Song(object):

   def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print line
    def sing_me_a_reverse_song_1(self):
        self.lyrics.reverse()
            for line in self.lyrics:
                print line
    def sing_me_a_reverse_song_2(self):
        for line in reversed(self.lyrics):
            print line
    def sing_me_a_reverse_song_3(self):
        for line in self.lyrics[::-1]:
            print line

bulls_in_parade = Song(["They rally around the family",
                    "with pockets full of shells"])
#sing it for me
bulls_in_parade.sing_me_a_song()

#1st method of reversing:
bulls_in_parade.sing_me_a_reverse_song_1()

#2nd method of reversing:
bulls_in_parade.sing_me_a_reverse_song_2()

#3rd method of reversing:
bulls_in_parade.sing_me_a_reverse_song_3()


第一种反转方法确实很好,但是我不知道为什么我无法让这两种最后一种方法起作用。

这是我得到的输出:

They rally around the family
with pockets full of shells
----------
with pockets full of shells
They rally around the family
----------
They rally around the family
with pockets full of shells
----------
They rally around the family
with pockets full of shells


这是我想在输出中看到的内容:

They rally around the family
with pockets full of shells
----------
with pockets full of shells
They rally around the family
----------
with pockets full of shells
They rally around the family
----------
with pockets full of shells
They rally around the family


如果在一个单独的函数中定义最后两个方法,它们将正常工作,但我不明白为什么它们在我的课堂上不起作用。

我认为问题应该出在“调用” lyrics上:

self.lyrics()


如果是这样,请帮助我解决此问题。

而且我还必须补充一点,我正在使用python 2.7

最佳答案

好吧,实际上他们确实在工作。

问题是您是第一次更改了数据成员。
您键入self.lyrics.revese(),此后此列表将保持反向。

您可以像这样修复方法:

def sing_me_a_reverse_song_1(self):
    tmpLyrics = self.lyrics[:]
    tmpLyrics.reverse()
    for line in tmpLyrics:
        print line


注意:

不要做tmpLyrics = self.lyrics因为python通过引用传递列表,因此正确的方法是tmpLyrics = self.lyrics[:]

09-20 20:14