Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13594

Python classes and __init__ method

I am learning python via dive into python. Got few questions and unable to understand, even through the documentation.

1) BaseClass

2) InheritClass

What exactly happens when we assign a InheritClass instance to a variable, when the InheritClass doesn't contain an __init__ method and BaseClass does ?

Actually the fileInfo.py example is giving me serious headache, i am just unable to understand as to how the things are working. Following

Upvotes: 5

Views: 3003

Answers (2)

bdeniker
bdeniker

Reputation: 1045

@FogleBird has already answered your question, but I wanted to add something and can't comment on his post:

You may also want to look at the super function. It's a way to call a parent's method from inside a child. It's helpful when you want to extend a method, for example:

class ParentClass(object):
    def __init__(self, x):
        self.x = x

class ChildClass(ParentClass):
    def __init__(self, x, y):
        self.y = y
        super(ChildClass, self).__init__(x)

This can of course encompass methods that are a lot more complicated, not the __init__ method or even a method by the same name!

Upvotes: 4

FogleBird
FogleBird

Reputation: 76852

Yes, BaseClass.__init__ will be called automatically. Same goes for any other methods defined in the parent class but not the child class. Observe:

>>> class Parent(object):
...   def __init__(self):
...     print 'Parent.__init__'
...   def func(self, x):
...     print x
...
>>> class Child(Parent):
...   pass
...
>>> x = Child()
Parent.__init__
>>> x.func(1)
1

The child inherits its parent's methods. It can override them, but it doesn't have to.

Upvotes: 6

Related Questions