newb __init__ inheritance

Colin J. Williams cjw at ncf.ca
Sat Mar 10 12:58:55 EST 2012


On 08/03/2012 10:25 AM, hyperboogie wrote:
> Hello everyone.
>
> This is my first post in this group.
> I started learning python a week ago from the "dive into python" e-
> book and thus far all was clear.
> However today while reading chapter 5 about objects and object
> orientation I ran into something that confused me.
> it says here:
> http://www.diveintopython.net/object_oriented_framework/defining_classes.html#fileinfo.class.example
>
> "__init__ methods are optional, but when you define one, you must
> remember to explicitly call the ancestor's __init__ method (if it
> defines one). This is more generally true: whenever a descendant wants
> to extend the behavior of the ancestor, the descendant method must
> explicitly call the ancestor method at the proper time, with the
> proper arguments. "
>
> However later on in the chapter:
> http://www.diveintopython.net/object_oriented_framework/userdict.html
>
> it says:
> "Methods are defined solely by their name, and there can be only one
> method per class with a given name. So if a descendant class has an
> __init__ method, it always overrides the ancestor __init__ method,
> even if the descendant defines it with a different argument list. And
> the same rule applies to any other method. "
>
> My question is if __init__ in the descendant class overrides __init__
> in the parent class how can I call the parent's __init__ from the
> descendant class - I just overrode it didn't I?
>
> Am I missing something more fundamental here?
> Thanks

The mro function [Method Resolution Order]is not too well advertised in 
the docs.  This should illustrate its usage:

#!/usr/bin/env python

class A():
   def __init__(self):
     z= 1

   def ringA(self):
     print ('aaa')

   def ringB(self):
     print('bbb')

class B(A):
   def __init__(self):
     z= 2

   def ringB(self):
     print('BBB')

a= A()
b= B()
b.ringB()
b.ringA()
b.__class__.mro()[1].ringB(b)

z= 1
def main():
     pass

if __name__ == '__main__':
     main()
I'm not sure that the class initialization is required.

Good luck,

Colin W.



More information about the Python-list mailing list