A Methodical Approach


#1

Hi,I can't understand why we didn't give our description method a name and an age parameters despite that when we called it python could use the information we saved in our hippo variable and printed them when we used it to call the description method so how is this possible and description doesn't know what name and age are ?Please explain and thank.


#2

I'm afraid I do not know which exercise you are referring to. I'd love to help, but I need context to understand what you are talking about.


#3

Introduction to classes - methodical approach


#4

Let's see... When we call

hippo = Animal("Hippo Jr.",2)

The code creates a new hippo with two variables specifically defined inside of it: name and age, which can be directly accessed only within the instance of Animal (our little Hippo Jr.) by the code self.name and self.age.

The description method has the implicit argument (input) self, which is the instance of Animal that it is being called on.

When the code inside of description then uses self.name and self.age, it sees the variables defined when the instance was being made through the __init__() method and then uses them.

Thus,

hippo  = Animal("Hippo Jr.",2)
hippo.description()

first creates an instance of Animal with internal variables name and age set to "Hippo Jr." and 2, respectively, then prints out the values stored in the variables name and age to the console.

Does this help or have I been rambling senselessly?


#5

description is a method of the class, and is accessible to all instances. As mentioned above, each instance has its own defined member variables. Internally, the class uses self to reference the current owner (the instance on which the method is called, or context ).

def description(self):
    print "My name is, %s, and my age is, %d" % (self.name, self.age)

Now when we call this method on hippo, that instance becomes the context (self).

hippo.description()

Think of the internal representation as,

"My name is, %s, and my age is, %d" % (hippo.name, hippo.age)

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.