super() is super [was Re: Calling dunder methods manually]

Steve D'Aprano steve+python at pearwood.info
Sat Apr 15 20:35:04 EDT 2017


On Sat, 15 Apr 2017 10:50 pm, Rick Johnson wrote:

> Even to this day, i avoid super because the
> semantics are confusing, 

If super() is confusing, it is because *inheritance* is confusing, and that
goes triple for multiple inheritance. If it is not *easy* to use super() to
manage your class' inheritance, that's a sign that your class hierarchy is
complicated and confusing and you're in a nightmare whether you use super()
or not.

But for the simple cases, using super() in Python 3 couldn't be easier. If
you have code that looks something like this:


class MyClass(ParentClass):
    def method(self, arg):
        result = ParentClass.method(self, arg)


you replace the last line with:

        result = super().method(arg)


If you have:

class MyClass(A, B):
    def method(self, arg):
        A.method(self, arg)
        B.method(self, arg)


you replace the last two lines with:

        super().method(arg)


See also:

https://rhettinger.wordpress.com/2011/05/26/super-considered-super/



> eaisier to just write the path in long-form.

Easier and wrong.

If you have multiple inheritance, and don't use super(), then your code is
buggy, whether you have realised it or not.

Manually calling your parent class is only acceptable if you can absolutely
guarantee that your class, all its parent classes, and all its subclasses
will ONLY use single inheritance.





-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list