[ACCEPTED]-Is it a good idea to use super() in Python?-super
The book Expert Python Programming has discussed the topic of "super 9 pitfalls" in chapter 3. It is worth 8 reading. Below is the book's conclusion:
Super 7 usage has to be consistent: In a class hierarchy, super 6 should be used everywhere or nowhere. Mixing 5 super and classic calls is a confusing practice. People 4 tend to avoid super, for their code to be 3 more explicit.
Edit: Today I read this part 2 of the book again. I'll copy some more sentences, since 1 super usage is tricky:
- Avoid multiple inheritance in your code.
- Be consistent with its usage and don't mix new-style and old-style.
- Check the class hierarchy before calling its methods in your subclass.
You can use super, but as the article says, there 7 are drawbacks. As long as you know them, there 6 is no problem with using the feature. It's 5 like people saying "use composition, not 4 inheritance" or "never use global variables". If 3 the feature exists, there is a reason. Just 2 be sure to understand the why and the what 1 and use them wisely.
super() tries to solve for you the problem 6 of multiple inheritance; it's hard to replicate 5 its semantics and you certainly shouldn't 4 create any new semantics unless you're completely 3 sure.
For single inheritance, there's really 2 no difference between
class X(Y): def func(self): Y.func(self)
class X(Y): def func(self): super().func()
so I guess that's 1 just the question of taste.
I like super() more because it allows you 3 to change the inherited class (for example 2 when you're refactoring and add an intermediate 1 class) without changing it on all the methods.
The problem people have with
super is more a 18 problem of multiple inheritance. So it is 17 a little unfair to blame
super multiple 16 inheritance is even worse. Michele Simionato 15 nicely wrapped this up in his blog article on super:
On 14 the other hand, one may wonder if all 13 super warts aren't hints of some serious 12 problem underlying. It may well be that 11 the problem is not with super, nor with 10 cooperative methods: the problem may be 9 with multiple inheritance itself.
So the 8 main lesson is that you should try to avoid 7 multiple inheritance.
In the interest of 6 consistency I always use super, even if 5 for single inheritance it does not really 4 matter (apart from the small advantage of 3 not having to know the parent class name). In 2 Python 3+
super is more convenient, so there 1 one should definitely use super.
Yes, you should use
super() over other methods. This 9 is now the standard object inheritance model 8 in Python 3.
Just stick to keyword arguments 7 in your
__init__ methods and you shouldn't have 6 too many problems. Additionally you can 5 use
**kwargs to support additional parameters that 4 are not defined in levels of the inheritance 3 chain.
I agree that it is brittle, but no 2 less so than using the name of the inherited 1 class.
More Related questions