Question about inheritence

Fredrik Lundh fredrik at pythonware.com
Tue Jul 22 12:54:01 EDT 2008


Catherine Heathcote wrote:

> If I create a new class inherited from another with a constructor, what
> happens with the new class's constructer?

assuming that you mean "is it called or not?":

Python doesn't really have constructors; when you create an object, 
Python first creates the object and then calls the __init__ method, if 
available

that method is an ordinary method, and behaves like all other methods: 
if you override it, your version is used.  if you don't, the other one 
is used.

 >>> class Parent:
...     def __init__(self):
...         print "init parent"
...
 >>> class Child(Parent):
...     pass
...
 >>> o = Child()
init parent

 >>> class Child(Parent):
...     def __init__(self):
...         print "init child"
...
 >>> o = Child()
init child

if you want to override the parent's init method, but still use its 
functionality, you can add an explicit call to the method:

 >>> class Child(Parent):
...     def __init__(self):
...         Parent.__init__(self)
...         print "init child"
...
 >>> o = Child()
init parent
init child

since it's an ordinary method call, you don't have to initialize the 
parent the first thing you do.  you can also pass in any arguments you 
want (including arguments passed to the child constructor):

 >>> class OtherChild(OtherParent):
...     def __init__(self, a, b, c):
...         self.c = c
...         OtherParent.__init__(self, a + b)
...

there's even a common pattern for passing along *all* arguments, no 
matter what they are:

 >>> class OtherChild(OtherParent):
...     def __init__(self, *args, **kwargs):
...         # do something here
...         OtherParent.__init__(self, *args, **kwargs)
...         # do something else here
...

instead of explicitly naming the baseclass, you can use the "super" 
method to automatically look up the parent class, but this only works
if the parent class inherits from "object" or a subclass thereof:

 >>> class Parent(object):
...     def __init__(self):
...             print "init parent"
...
 >>> class Child(Parent):
...     def __init__(self):
...             super(Child, self).__init__()
...             print "init child"
...
 >>> o = Child()
init parent
init child

hope this helps!

</F>




More information about the Python-list mailing list