Mathieu
Mathieu

Reputation: 5756

Which one to use: super() or self.function() with function defined in the parent class

Let's consider the following dummy example:

class A:
    def __init__(self, a):
        self.a = a
        self.backup_a = a
        
    def reset_a(self):
        self.a = self.backup_a
        print ('Stop touching my stuff!')
        
class B(A):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b
        
var = A(2)
var.reset_a()

var = B(2, 4)
var.f()

To add a method to B which uses the method reset_a from A, boh syntax with super(). or self. works. Which one is more correct and why?

class B(A):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b
        
    def f(self):
        self.reset_a()

OR

class B(A):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b
        
    def f(self):
        super().reset_a()

Upvotes: 3

Views: 659

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 52009

Inheritance automatically makes all methods ("functions") of the parent available to the child. However, if the child re-implements a method, this hides the parent method for the child.

  • Use self.method to access a method regardless whether it was defined in the child or parent.
  • Use super().method to explicitly skip the method defined by the child, and access the parent method instead.

In general, a method should use self.method to access other methods but super().method to access its own parent definition.

This is because in deep inheritance, a method cannot rely on whether/how another method has been overriden – only that methods of well-behaved child classes are indistinguishable from methods of the parent class. A method can only reliably know that it does itself override its own parent method.

Upvotes: 5

Related Questions