Doubt about Python derived class initialization

Asked

Viewed 180 times

2

Imagine I have a base class Food and create a second class Rice that will inherit the class functionalities Food.

If at the time of initializing, what difference does it make if I do:

class Rice(Food):
    def __init__(self):
        super().__init__()

or make:

class Rice(Food):
    def __init__(self):
        Food.__init__(self)

It’s the same?

2 answers

3


In your example, there is no difference, it is the same thing. The difference only appears when you use diamond-shaped multiple inheritance:

    A
  /   \
 B     C
  \   /
    D

class A:
    def teste(self):
        print("teste em A")

class B(A):
    def teste(self):
        print("teste em B")
        super().teste() # Equivalente a A.teste(self)

class C(A):
    def teste(self):
        print("teste em C")
        super().teste() # Equivalente a A.teste(self)

class D(B, C):
    def teste(self):
        print("teste em D")
        super().teste() # ?????????????????

d = D()
d.teste()

As the class D inherits so much of B how much of C, within the method D.teste you would have to call both methods C.teste(self) and B.teste(self), however, as each of these calls A.teste, the result without using the super()would it be that A.teste would be called twice.

The solution is the super() - it serves for each ancestral method to be called only once, in order of definition.

The exit will be:

teste em D
teste em B
teste em C
teste em A

0

The super() is used between inheritances of classes, it provides us to extend/subscribe methods from a super class (parent class) to a sub class (daughter class), through it we define a new behavior for a certain method built in the parent class and inherited by the daughter class.

To better understand, consider the code below as an example:

Python 2

class Pai(object):
  def __init__(self):
    print('Construindo a classe Pai')

class Filha(Pai):
  def __init__(self):
    super(Filha, self).__init__()

Python 3

class Pai(object):
  def __init__(self):
    print('Construindo a classe Pai')

class Filha(Pai):
  def __init__(self):
    super().__init__()
  • Thank you! I understood the purpose of using the super(), but what I’d really like to know is the difference between the two ways of using that I mentioned in the question.

  • The answer, although correct and contain information on the super(), does not correspond to the question asked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.