using super

Duncan Booth duncan.booth at invalid.invalid
Mon Jan 18 19:11:14 CET 2010


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) ...



More information about the Python-list mailing list