[Tutor] calling the constructor of an inherited class

Magnus Lyckå magnus@thinkware.se
Thu May 29 13:12:01 2003


At 15:27 2003-05-29 +0800, ali mangaliag wrote:
>class x:
>     def __init__(self, a):
>         self.a = a
>
>class x(y):
>     def __init__(self):
>         # how can i call the constructor of class x???

Don already gave you the answer  for old style classes, but
for new classes, i.e.  classes that inherit from object, or
from a built in type such  as file or float etc, there is a
new function called super. It will determine from what base
class to choose the (in this case) __init__ method. This is
more important if you use multiple inheritance. See
http://www.python.org/doc/2.2.2/whatsnew/whatsnew22.html

 >>> class A(object):
...     def __init__(self):
...             print "A constructor"
...
 >>> class B(A):
...     def __init__(self):
...             print "B constructor"
...             super(B, self).__init__()
...
 >>> a = A()
A constructor
 >>> b=B()
B constructor
A constructor


--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program