using super
Jean-Michel Pichavant
jeanmichel at sequans.com
Mon Jan 18 14:50:45 EST 2010
Duncan Booth wrote:
> Jean-Michel Pichavant <jeanmichel at sequans.com> wrote:
>
>
>>>>> class SubClass(Base):
>>>>> colour = "Red"
>>>>> def parrot(self):
>>>>> """docstring for Subclass"""
>>>>> return super(Subclass, self).parrot()
>>>>>
>> I'm not a big fan of super, but I'm still wondering if
>>
>>
>>>>> return super(self.__class__, self).parrot()
>>>>>
>> would have made it.
>>
>
> No, it wouldn't.
>
>
>> What if Subclass has more than one base class ?
>>
>
> super() will work in that case provided you specify the current class. It
> never works correctly if you specify the class of self.
>
> Consider another level of subclasses and it may be clearer:
>
>
>>>> class Base(object):
>>>>
> def parrot(self):
> print "Base.parrot"
>
>
>
>>>> class SubClass(Base):
>>>>
> def parrot(self):
> print "SubClass.parrot"
> return super(SubClass, self).parrot()
>
>
>
>>>> class SubSubClass(SubClass):
>>>>
> def parrot(self):
> print "SubSubClass.parrot"
> return super(SubSubClass, self).parrot()
>
>
>
>>>> SubSubClass().parrot()
>>>>
> SubSubClass.parrot
> SubClass.parrot
> Base.parrot
>
>
>>>> class SubClass(Base):
>>>>
> def parrot(self):
> print "SubClass.parrot"
> return super(self.__class__, self).parrot()
>
>
>
>>>> class SubSubClass(SubClass):
>>>>
> def parrot(self):
> print "SubSubClass.parrot"
> return super(self.__class__, self).parrot()
>
>
>>>> SubSubClass().parrot()
>>>>
> SubClass.parrot
> SubClass.parrot
> SubClass.parrot
> SubClass.parrot
> SubClass.parrot
> SubClass.parrot
> SubClass.parrot
> SubClass.parrot
> SubClass.parrot
> ... (you're in an infinite loop now) ...
>
I see.
Then is there a reason why
>>> return super(Subclass, self).parrot()
would be prefered over the "classic"
>>> return Base.parrot(self)
?
Or is it just a matter of preference ?
JM
More information about the Python-list
mailing list