Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to use super() in Python?

Tags:

python

oop

super

Or should I just explicitly reference the superclasses whose methods I want to call?

It seems brittle to repeat the names of super classes when referencing their constructors, but this page http://fuhm.net/super-harmful/ makes some good arguments against using super().

like image 569
Josh Gibson Avatar asked Aug 11 '09 10:08

Josh Gibson


2 Answers

I like super() more because it allows you to change the inherited class (for example when you're refactoring and add an intermediate class) without changing it on all the methods.

like image 140
juanjux Avatar answered Oct 06 '22 17:10

juanjux


super() tries to solve for you the problem of multiple inheritance; it's hard to replicate its semantics and you certainly shouldn't create any new semantics unless you're completely sure.

For single inheritance, there's really no difference between

class X(Y):
    def func(self):
        Y.func(self)

and

class X(Y):
    def func(self):
        super().func()

so I guess that's just the question of taste.

like image 29
ilya n. Avatar answered Oct 06 '22 17:10

ilya n.