user3768495
user3768495

Reputation: 4667

How to properly initiate a child class by inheritance in python?

The title is probably not quite precise-sorry. I am practicing python class and wrote something like this:

class parent():
    def __init__(self, lastname,eyecolor):
        print "Parent class initiated!"
        self.lastname=lastname
        self.eyecolor=eyecolor

    def show_info(self):
        print("PARENT CLASS INFO:")
        print ("Lastname is:  "+self.lastname)

class child(parent):
    like_to = ['crawl', 'laugh', 'eat']
    def __init__(self, lastname, eyecolor, n_toys=10):
        parent.__init__(self, lastname, eyecolor)
        self.n_toys=n_toys

    def show_info(self):
        print ("CHILD CLASS INFO:")
        print("Child has %d toys" % self.n_toys)

Then I did:

from utils import parent, child

father=parent('Jackson', 'black')
father.show_info()
son=child('Jackson','black')
son.show_info()

I basically followed a tutorial so above codes worked well. Then I realized that if I comment out the

parent.__init__(self, lastname, eyecolor)

line in the child class, the codes still works.

So, what does this line do exactly? What are the differences, if any, with or without this line?

Upvotes: 1

Views: 96

Answers (1)

Anish Silwal
Anish Silwal

Reputation: 980

parent.__init__(self, lastname, eyecolor)

The line calls the super method __init__ and initializes the lastnameand eyecolor

If you comment this line:

//parent.__init__(self, lastname, eyecolor)

then your object won't have members lastnameand eyecolor and you cannot access these members.

Explanation

When this line is called:

parent.__init__(self, lastname, eyecolor)

The __init__ method of parent class is called:

def __init__(self, lastname,eyecolor):
    print "Parent class initiated!"
    self.lastname=lastname   // initialize lastname
    self.eyecolor=eyecolor   // initialize eyecolor

Which will initialize members lastname and eyecolor.

But commenting the line will stop calling __init__ method of parent class but still works without crashing.

But this won't work when you comment that line:

son=child('Jackson','black')
son.show_info()
print(son.lastname) // won't work because lastname is not initialized
print(son.eyecolor) // won't work because eyecolor is not initialized

Upvotes: 1

Related Questions