I had a problem with this one too. But, it makes sense now.
Often the best way to see if I understand something is to try explaining it to others. Here goes nothing.
The original version of the code makes a Song() class for each set of lyrics. I’ll just do the remarkably-similar-to-the-birthday-song for the sake of brevity:
happy_bday = Song(["Happy birthday to you.",
"I don't want to get sued",
"So I'll stop right there."])
Later, you call the “sing()” method like this:
happy_bday.sing_me_a_song()
which I’d translate to something like “In the Song() class called happy_bday, trigger the ‘sing_me_a_song’ method. It will print out the lyrics passed to the Song() earlier, line by line.”
But now we want to put the lyrics in a variable. I did it in 3 major changes.
First, I changed the way happy_bday_lyrics was set up:
happy_bday_lyrics = ("Happy birthday to you.",
"I don't want to get sued",
"So I'll stop right there.")
That is, I made it a variable containing a tuple of strings, instead of an instance of Song() (I think).
Finally, the following two lines:
bday = Song(happy_bday_lyrics)
Passes the birthday-song-like-song lyrics to Song().
bday.sing()
Calls the sing() method (I renamed it because I got tired of typing out sing_me_a_song) within the Song() class, which prints the text within happy_bday_lyrics line-by-line. For instance:
Happy birthday to you.
I don’t want to get sued.
So I’ll stop right there.
FWIW, here’s my customized version of the Song() class:
class Song(object):
def __init__(self,lyrics):
self.lyrics = lyrics
def sing(self):
for line in self.lyrics:
print line
print "\n"
I added the \n at the end to create a blank line between printings of song lyrics, just for the sake of formatting. However it results in TWO blank lines. Not yet sure why.
P.S.: I also tried happy_bday_lyrics as a list (using []) and a dict (using {} and adding some keys, for which I used line numbers e.g. ‘1’, ‘2’, ‘3’).
If you make the lyrics a list, no problem.
If you make the lyrics a dict, weird stuff happens. For me, it printed the lines of happy_bday_lyrics out of order. For instance, if I defined:
happy_bday_lyrics = {"Happy birthday to you.":'1',
"I don't want to get sued.":'2',
"So I'll stop right there.":'3'}
I got the print out:
So I’ll stop right there.
Happy birthday to you.
I don’t want to get sued.
That is, order came out as 3, 1, 2 instead of 1, 2, 3. I don’t know why that exact order, but I’m sure it has something to do with dicts having no ordering (as mentioned in the last couple of lessons).