[Tutor] super() vs. explicitly calling base class?

Mats Wichmann mats at wichmann.us
Sat Sep 21 11:31:15 EDT 2019


On 9/20/19 10:47 PM, boB Stepp wrote:
> Python 3.7.4 on Linux Mint
> 
> Assumption:  I have only TWO classes (Not concerned about 3+ class
> inheritance scenario), Base and Child.  Is there any advantage to
> using super() over explicitly calling Base from within Child?  My
> following trivial example does not suggest any difference:

The difference is that one way is hardwired and the other (as befits a
dynamic language) is a computed indirect reference. That means in
addition to protecting you from having to change references if you
change the class hierarchy, you also have the opportunity to influence
the way it resolves to the class it will delegate to.

If all that sounds too much it may actually be: if you *really* know for
sure there will only ever be these two classes and you know exactly how
they will be used, then fine, hardwire the relationship.  There are some
people who don't think super is useful.  There's a famous paper that was
written under the title "Python's Super Considered Harmful" - the author
later retitled it "Python's Super is nifty, but you can't use it".
Naturally, there's also work entitled "Super Considered Super"!

Would just like to remind: that function there which prints "This is the
Base class!" - isn't really "in" it.  The def statement causes a
function object to be created, and a reference to that function object,
with the name "__init__", goes into the dictionary that was created by
the Base class definition. But it has no phyical attachment to Base...
all it knows about is the instance object (plus remaining args - none in
this case) it is passed - and the 2nd and 3rd times it runs it is
actually running with a Child object. That makes zero difference if the
work you're asking it to do is print a string, but it does have
implications in designing more complex methods if super is going to be
in play.  In particular, it means harmonizing the way arguments are
handled by methods of the same name in a class hierarchy. Classes are
... "different" in Python :)


>>>> class Base:
>     def __init__(self):
>         print("This is the Base class!")
>>>> class Child(Base):
>     def __init__(self):
>         print("This is the Child class!")
>     def call_base(self):
>         print("About to call the Base class with super!")
>         super().__init__()
>         print("Now explicitly calling the Base class!")
>         Base.__init__(self)
>>>> a = Base()
> This is the Base class!
>>>> b = Child()
> This is the Child class!
>>>> b.call_base()
> About to call the Base class with super!
> This is the Base class!
> Now explicitly calling the Base class!
> This is the Base class!
> 



More information about the Tutor mailing list