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

Chris Angelico rosuav at gmail.com
Sat Apr 15 20:49:42 EDT 2017


On Sun, Apr 16, 2017 at 10:35 AM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
>
>> 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.

Plus, it's fragile in that it names the parent class everywhere.

class A:
    def __init__(self): ...
    def __add__(self, other): ...
    def __or__(self, other): ...

class B(A):
    def __init__(self):
        A.__init__(self)
    def __add__(self, other):
        A.__add__(self, other)
    ...

Every method you subclass-and-call-parent needs to say the name of the
parent class. With super, they all just say super(). I know which one
I'd rather do.

ChrisA



More information about the Python-list mailing list