Reputation: 588
I'm trying to learn class
in Python
and here is an exercise I have made for myself. I want to create a class that can sing a song regularly and also sing a song in reverse. So here is what I typed:
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()
The first method of reversing works really well, but I don't know why I can't get those two last methods to work.
here is what I get in output:
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
and here is what I want to see in my output:
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
If you define the last two methods in a separated function, they will work properly but I can't understand why they don't work in my class.
I thing that the problem should be with 'calling' lyrics
:
self.lyrics()
If so help me out solving this.
And also I have to add that I'm using python 2.7
Upvotes: 2
Views: 616
Reputation: 10641
well, actually they do work..
the problem is that you changed your data member at the first time. you typed self.lyrics.revese(), since then, the list stays reversed.
you can fix the method like this:
def sing_me_a_reverse_song_1(self):
tmpLyrics = self.lyrics[:]
tmpLyrics.reverse()
for line in tmpLyrics:
print line
Note:
don't do tmpLyrics = self.lyrics
because python passes list by reference and thus the right way is tmpLyrics = self.lyrics[:]
Upvotes: 1
Reputation: 117926
They all work fine, it's just that your first method mutates the list, so the others are reversing the already reversed list, so they effectively are back to their original order!
def sing_me_a_reverse_song_1(self):
self.lyrics.reverse() # <----- lyrics is now reversed
for line in self.lyrics:
print line
After you call this method, any other time you try to access self.lyrics
it will still be reversed (unless you reverse it back to it's original order)
Upvotes: 3