Search code examples
pythonpython-3.xsuper

How does calling super() with the 2-argument form differ from directly referencing the method and passing in "self" manually?


A bit of an odd question, consider the following code:

class A:
    def mymethod(self):
        return "mymethod from class A"
class B(A):
    def mymethod(self):
        return "mymethod from class B"
class C(B):
    # in this class I want "mymethod" to return the same string returned from mymethod in the A class, with 2 exclamation points (!!) appended
    # obviously this is a simplified example with dumb logic
    def mymethod(self):
        ss = super(B, self).mymethod()

        # OR

        ss = A.mymethod(self)

        return ss + " !!"           

I am fairly inexperienced when it comes to OOP so excuse me if the answer is extremely obvious.

As far as I can see, there is no difference between these 2 approaches, and as such I fail to understand how super() can be useful inside class methods.


Solution

  • Using super(B, self) removes a level of dependency. If the definition of B is changed to use a different superclass, you'll automatically call the method from that class. If you hard-code A.mymethod(self), you'll need to update that when B is redefined.