4

Why in super() keyword, can we omit self? What if we don't omit it?

class A:
  def __init__(self, var1, var2):
    """
    some code
    """

class B(A):
  def __init__(self, varA, varB):
    super().__init__(varA, varB)
    """
    some code
    """
Sharon Ng
  • 55
  • 11
  • 3
    Similar question with terrible answer: [Python: super and \_\_init\_\_() vs \_\_init\_\_( self )](//stackoverflow.com/q/7629556) – Aran-Fey Jul 26 '19 at 10:23
  • Possible duplicate of [What does 'super' do in Python?](https://stackoverflow.com/questions/222877/what-does-super-do-in-python) – Lev Rubel Jul 26 '19 at 10:33

1 Answers1

0
class Rectangle:
    def __init__(self, length, width):
    self.length = length
    self.width = width

    def area(self):
    return self.length * self.width

    def perimeter(self):
    return 2 * self.length + 2 * self.width

class Square(Rectangle):
    def __init__(self, length):
        super(Square, self).__init__(length, length)

In Python 3, the super(Square, self) call is equivalent to the parameterless super() call. The first parameter refers to the subclass Square, while the second parameter refers to a Square object which, in this case, is self. You can call super() with other classes as well:

class Cube(Square):
def surface_area(self):
    face_area = super(Square, self).area()
    return face_area * 6

def volume(self):
    face_area = super(Square, self).area()
    return face_area * self.length

You can find more details here

A.Rauan
  • 42
  • 3