instance attributes not inherited?

John M. Gabriele john_sips_teaz at yahooz.com
Mon Jan 16 07:44:40 CET 2006


Dennis Lee Bieber wrote:
> On Sun, 15 Jan 2006 20:50:59 -0500, "John M. Gabriele"
> <john_sips_teaz at yahooz.com> declaimed the following in comp.lang.python:
> 
> 
>>Sorry -- that question I wrote looks a little incomplete: what I meant
>>to ask was, how does it help this code to work:
>>
>>---- code ----
>>#!/usr/bin/python
>>
>>class Parent( object ):
>>     def __init__( self ):
>>         self.x = 9
>>         print "Inside Parent.__init__()"
>>
>>     def wash_dishes( self ):
>>         print "Inside Parent.wash_dishes(), washing", self.x, "dishes."
>>
>>
>>class Child( Parent ):
>>     def __init__( self ):
>>         super( Child, self ).__init__()
>>         print "Inside Child.__init__()"
>>
>>
>>c = Child()
>>c.wash_dishes()
>>---- /code ----
>>
>>since the x instance attribute created during the
>>super( Child, self ).__init__() call is just part of what looks to be
>>a temporary Parent instance.

(Whoops. I see now thanks to Dan Sommers' comment that there's
no temp Parent instance, unless the call to super() is creating
one...)

> 
> 	Because you passed the CHILD INSTANCE (self) to the method of the
> super... so "self.x" is "child-instance.x"

Huh? But it sounds by the name of it that super() is supposed to
return something like the superclass (i.e. Parent). You mean, that
super( Child, self ).__init__() call inside Child.__init__() leads
to Parent.__init__() getting called but with the 'self' reference
inside there referring to the Child object we named 'c' instead of
some Parent .... {confused}

Wait a second. I can replace that super() call with simply

     Parent.__init__( self )

and everything still works... and it looks to me that, indeed,
I'm passing self in (which refers to the Child object), and that
self gets used in that __init__() method of Parent's... Wow. I'd
never seen/understood that before! We're using superclass initializers
on subclasses that weren't around when the superclass was written!

I'm having a hard time finding the documentation to the super() function.
I checked the language reference ( http://docs.python.org/ref/ref.html )
but didn't find it. Can someone please point me to the relevant docs on
super?

help( super ) doesn't give much info at all, except that super is actually
a class, and calling it the way we are here returns a "bound super object",
but I don't yet see what that means (though I know what bound methods are).

Thanks,
---J

-- 
(remove zeez if demunging email address)



More information about the Python-list mailing list