使用类反转python中的字符串数组

使用类反转python中的字符串数组,python,arrays,class,python-2.7,arraylist,Python,Arrays,Class,Python 2.7,Arraylist,我正在尝试用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_m

我正在尝试用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
如果在一个单独的函数中定义最后两个方法,它们将正常工作,但我不理解它们为什么在我的类中不工作

我认为问题应该出在“呼叫”歌词上:

如果是这样,请帮我解决这个问题


我还必须补充一点,我使用的是python 2.7,事实上它们确实有效

问题是您第一次更改了数据成员。 你输入了self.lymps.revese,从那以后,列表一直颠倒

您可以按如下方式修复此方法:

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


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

它们都工作得很好,只是您的第一个方法改变了列表,所以其他方法正在反转已经反转的列表,所以它们实际上回到了原来的顺序

def sing_me_a_reverse_song_1(self):
    self.lyrics.reverse()  # <----- lyrics is now reversed
    for line in self.lyrics:
        print line
调用此方法后,其他任何时候尝试访问self.ly词时,它仍将被反转,除非您将其反转回原始顺序

def sing_me_a_reverse_song_1(self):
    self.lyrics.reverse()  # <----- lyrics is now reversed
    for line in self.lyrics:
        print line