i'm trying learn class in python , here exercise have made myself.i want create class can sing song regularly , sing song in reveres. here typed:
class song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): line in self.lyrics: print line def sing_me_a_reverse_song_1(self): self.lyrics.reverse() line in self.lyrics: print line def sing_me_a_reverse_song_2(self): line in reversed(self.lyrics): print line def sing_me_a_reverse_song_3(self): line in self.lyrics[::-1]: print line bulls_in_parade = song(["they rally around family", "with pockets full of shells"]) #sing 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() the first method of reversing works well, don't know why can't 2 last methods work.
here in output:
they rally around family pockets full of shells ---------- pockets full of shells rally around family ---------- rally around family pockets full of shells ---------- rally around family pockets full of shells and here want see in output:
they rally around family pockets full of shells ---------- pockets full of shells rally around family ---------- pockets full of shells rally around family ---------- pockets full of shells rally around family if define last 2 methods in separated function, work can't understand why don't work in class.
i thing problem should 'calling' lyrics :
self.lyrics() if me out solving this.
and have add i'm using python 2.7
well, work..
the problem changed data member @ first time. typed self.lyrics.revese(), since then, list stays reversed.
you can fix method this:
def sing_me_a_reverse_song_1(self): tmplyrics = self.lyrics[:] tmplyrics.reverse() line in tmplyrics: print line note:
don't tmplyrics = self.lyrics because python passes list reference , right way tmplyrics = self.lyrics[:]
Comments
Post a Comment