[Tutor] Re: Class - superclass
Andrei
project5 at redrival.net
Fri Apr 8 21:48:04 CEST 2005
Bernard Lebel wrote on Fri, 8 Apr 2005 15:05:13 -0400:
> I'm experimenting with basic inheritance concepts, and something that
> I would assume to work returns an error.
>
>>>> class A:
> ... def __init__( self ):
> ... self.a = 13
> ...
>>>> class B( A ): # create sub-class of class A
> ... def __init__( self ):
> ... self.b = 14
Call the __init__ of the ancestor explicitly:
>>> class B(A):
... def __init__(self):
... A.__init__(self)
... self.b = 14
>>> b = B()
>>> b.a, b.b
(13, 14)
B inherits everything from A, but by defining B.__init__, the __init__
inherited from A is replaced, so you'll need to call it explicitly. Python
has no way of knowing that you still want to use the original __init__ too
unless you tell it so. To demonstrate the fact that __init__ is indeed
inherited:
>>> class C(A):
... pass
>>> c = C() # inherited __init__ (A.__init__) is called
>>> c.a
13
--
Yours,
Andrei
=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
More information about the Tutor
mailing list