classes riddle

Dave Angel davea at
Mon Oct 19 21:50:27 CEST 2009

inhahe wrote:
> Can somebody clear this up for me?
> ------
> Class B(A): def __init__(self, a) A.__init__(a) self.a = a a = A() ba = B(a)
> bc = B(a) bd = B(a) ------ I'm not sure what A.__init__ here does. I would
> think its __init__ is designed specifically to run once for any given
> object.. so i'm not sure what happens. and if A calls self.blah(), which
> instance of B which overrides blah gets called?
This won't run, for a pile of reasons, starting with formatting.  Try 
posting properly indented code, with capitalization correct, and without 
missing colons.

But your first question isn't too hard.  The __init__() method of each 
class runs when an instance (object) of that class is created.  But if 
you inherit from another class, and that class needs arguments, you have 
to call its __init___() method as well.  You use the A. qualifier so 
that the compiler knows which __init__ method to invoke.

Your second question doesn't make sense.  "A calls self.blah()"  ??   
you seem to be saying that the class calls some method? 

"which instance... gets called" ???  Instances don't get called.

Perhaps your question is what happens when a method of A calls another 
method of A, where the same method name occurs (override) in B.  The 
answer to which instance of B is used depends simply on which instance 
of B was used for the original method call.  And in fact which method is 
called also depends on whether the instance is of type A or type B.

Best to give definitions of two classes (with proper indentation), where 
A has two methods, and B only overrides one of them.  Then you can state 
your question more concretely, or even try it to see.  In fact, by the 
time you spell it out completely, the answer could very well be obvious 
to you.


More information about the Python-list mailing list