Calling __init__ for all mixins

David Bolen db3l at fitlinxx.com
Wed Aug 18 18:12:14 EDT 2004


Martin Maney <maney at pobox.com> writes:

> I've been to the cookbook (both forms, since they're sometimes usefully
> different), but that gave rise to more questions than answers.  Heck,
> let me pull some of them up while I'm at it.
> 
> Martelli gives the recipie (5.3 on paper) "Calling a Superclass
> __init__ Method if it Exists" where he seems to say that this:
> 
> class NewStyleOnly(A, B, C):
> 	def __init__(self):
> 		super(NewStyleOnly, self).__init__()
> 
> is the New Class Speak equivalent of
> 
> class Classic(A, B, C):
> 	def __init__(self):
> 		for base in self.__class__.__bases__:
> 			if hasattr(base, '__init__'):
> 				base.__init__(self)
> 
> but when I tried a simple test case (base classes just print a tracer
> when called), Martelli's NewStyleOnly only invoked A.__init__, as it
> was the first base class in the base list as written with an __init__
> implemented.  These seem to me to be very different.

Can you show your test code.  I've found that you may need to ensure
all of your classes are cooperating in their use of super(), as in the
following:

    mro.py:

    class A(object):

        def __init__(self):
            print "A init"
            super(A,self).__init__()

    class B(object):

        def __init__(self):
            print "B init"
            super(B,self).__init__()

    class C(object):

        def __init__(self):
            print "C init"
            super(C,self).__init__()


    class Mix(A,B,C):

        def __init__(self):
            print "Mix init"
            super(Mix,self).__init__()


    Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import mro
    >>> mro.Mix()
    Mix init
    A init
    B init
    C init
    <mro.Mix object at 0x0081EB48>
    >>>

The new style MRO approach will only work if all of your objects are
new style classes and they all participate in the cooperative process
through the use of super().  Also, the precise MRO used has changed
between 2.2 and 2.3 but it shouldn't affect the above syntax.

I do think it's easy to find yourself skipping the call to object's
__init__ in classes since it doesn't necessarily do anything, but it's
those other super calls that provide the chance to iterate through the
inheritance hierarchy based on the initial call from the ultimate
subclass.

Guido has some info on the cooperative use of super in his 2.2
unification draft available at http://www.python.org/2.2.3/descrintro.html
and more info on the MRO change is at http://www.python.org/2.3/mro.html.

-- David



More information about the Python-list mailing list