[Tutor] inheriting from a class

Alan Gauld alan.gauld at btinternet.com
Fri Sep 26 01:54:40 CEST 2008

"Christopher Spears" <cspears2002 at yahoo.com> wrote

> class TransCircle(collisionObjects.Circle):
>    def __init__(self):
>        collisionObjects.Circle.__init__(self)
>        self.image.set_colorkey((255, 255, 255))
> Basically, he is creating a TransCircle class that inherits
> attributes from a Circle class inside the collisionObjects module.
> Is calling Circle's constructor inside of TransCircle's constructor
> necessary for inheritance to work?

No its not necessary,  but its a very good idea.

Essentially if the super class does any initialisation of its 
in its init method then if you don't call it from the sub class then 
initialisation will not be done. So if you want to risjk using an 
where some of the attributes don't exist or have unpredictable values
go ahead, but don't expect your code to work smoothly! Or 
you could find out what the super class init does and do it all 
but thats a lot of work and if you get the sequence wrong it could 

> Here is a little test that I ran:
> In [2]: class A:
>   ...:     def __init__(self):
>   ...:         print "Class A!"
>   ...:

This initialiser doesn't initialise anything Try it with:

> In [2]: class A:
>    ...:     def __init__(self, message="Class A"):
                  self.message = message
>   ...:         print self.message
>   ...:

> In [3]: class B (A):
>   ...:     def __init__(self):
>   ...:         print "Class B!"

Again no initialisation here.

> In [3]: class B (A):
>   ...:     def __init__(self):
>   ...:         print "Class B message:", self.message

> In [4]: a = A()
> Class A!
> In [6]: b = B()
> Class B!
> Looks like I don't have to call A's constructor.
> Or am I missing something?

No if the init doesn't actually initialise anything then you don't 
need to call it.
But note that even here the behaviour is different. If you had called 
A.init you
would have had 2 print statements not one from B.

Using my version above, if you miss out the call to A.init you get an
error because self.message is undefined...

The purpose of initialisation is to set state not normally to just
print messages.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list