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.
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.
Introduction to classes - methodical approach
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:
age, which can be directly accessed only within the instance of
Animal (our little Hippo Jr.) by the code
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.age, it sees the variables defined when the instance was being made through the
__init__() method and then uses them.
hippo = Animal("Hippo Jr.",2) hippo.description()
first creates an instance of
Animal with internal variables
age set to
"Hippo Jr." and
2, respectively, then prints out the values stored in the variables
age to the console.
Does this help or have I been rambling senselessly?
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).
Think of the internal representation as,
"My name is, %s, and my age is, %d" % (hippo.name, hippo.age)
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.