super or not super?

Rhodri James rhodri at kynesim.co.uk
Fri Jul 12 11:20:13 EDT 2019


On 12/07/2019 15:12, Paulo da Silva wrote:
> Hi all!
> 
> Is there any difference between using the base class name or super to
> call __init__ from base class?
> 
> class C1:
> 	def __init__(self):
> 		...
> 
> class C2(C1):
> 	def __init__(self):
> 		C1.__init__(self) or super().__init__() ??
> 		...
> 
> I have been using super, but I see some scripts where the base class
> name is used.

For a simple single inheritance case like this there isn't any 
difference, but using super() a good habit to get into.  Mostly it makes 
code maintenance easier: if you suddenly decide to change your base 
class to C3 (say for debug purposes), you only have to change one line:

class C3:
     def __init__(self):
         ...

class C2(C3):
     def __init__(self):
         super().__init__()

Using the base class by name can lead to errors like this:

class C2(C3):
     def __init__(self):
         C1.__init__(self)  # Whoops, forgot this one

super() also has major advantages if you are stuck with multiple 
inheritance.  Raymond Hettinger has an excellent article on this here:
https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

-- 
Rhodri James *-* Kynesim Ltd



More information about the Python-list mailing list