Question

Please see the questions below -

class Song(object):

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

    def sing_me_a_song(self):
        for line in self.lyrics:
            print line

happy_bday = Song(["Happy birthday to you",
                   "I don't want to get sued",
                   "So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family",
                        "With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()
  1. In both the def, I see lyrics (line 3, 5 and 6). Why? What is really happening there?

  2. The name of the class is Song. On line 8 and 11, there is "Song" on the right side of the variable. Why? I really don't get it.

  3. Put the lyrics in a separate variable, then pass that variable to the class to use instead. How would I do that?

This is very important for me, as I just started OOP. Please be patient with me, and answer the above questions.

Was it helpful?

Solution

Firstly, linking to the original example is a good idea. I am using line numbers from the original example.

  1. Lines 1 to 8 define a class called Song. A class is exactly like a blueprint for making a new object. Every function that you add to a class will be added to the object when you make the object.

  2. Song is on the right side on line 10 and 14 because you are making new Song objects, and putting them in variables. You don't even need to put the Song object inside a variable. The following would work just fine:

    Song(["Do","Re","Mi"]).sing_me_a_song()

  3. What is the difference between this:

    print("Hi!")

    And this?

    message = "Hi!"

    print(message)

    In the one you pass a value directly, and in the other you pass a variable that contains the value. Just like "Hi!" is a value, ["Do","Re","Mi"] is a value too. How would you pass the second value to a new Song object?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top