8. A methodical approach


#1

https://www.codecademy.com/courses/python-intermediate-en-WL8e4/1/3?curriculum_id=4f89dab3d788890003000096#

I expect this to throw an error as I am defining the description() function after initialisation init(), but this works perfectly fine. I do not understand how does description() gives the results as the attributes are initialised afterwards.
Please explain.

class Animal(object):
    """Makes cute animals."""
    is_alive = True
    def description(self):
        print self.name
        print self.age
    def __init__(self, name, age):
        self.name = name
        self.age = age
   
Hippo= Animal("hippo","2")
Hippo.description()

#2

First thing to understand.
Adding init method to a class is not mandatory.
But When you add it,It just act like a constructor,that used to activate property of a class when you create instances/Objects from it.

so when you do this ..

Hippo= Animal("hippo","2")
pass "hippo" and 2..
Then it uses init method to transfer those values.
Now our Hippo instance have name and age, when we call our method..description()
It can access those properties(name and age) and print them.

More about init and self..


#3

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