0

I want to call the super method from B of an instance object of the derived class in the following fashion:

class B:
    pass

class A(B):
    pass

a_object = A()
a_object.super().__init__()

I get the following error:

AttributeError: 'A' object has no attribute 'super'

Is there a way I can call super method in this way?

David
  • 2,926
  • 1
  • 27
  • 61

2 Answers2

2

I found a way using:

super(A, a_object).__init__()
David
  • 2,926
  • 1
  • 27
  • 61
2

As you've already found the answer, you know you could use super(ChildClass, self).__init__(). I would like to explain how it works using a simple example. In the below piece of code, I have called __init__ of BaseClass in the __init__ of ChildClass.

class BaseClass(object):
    def __init__(self, *args, **kwargs):
        pass

class ChildClass(BaseClass):
    def __init__(self, *args, **kwargs):
        #Calling __init__ of BaseClass
        super(ChildClass, self).__init__(*args, **kwargs)

For example:

#Here is simple a Car class
class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

#Inherit the BaseClass here
class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        #calling the __init__ of class "Car"
        super(ElectricCar, self).__init__(model, color, mpg)

#Instantiating object of ChildClass
car = ElectricCar('battery', 'ford', 'golden', 10)
print(car.__dict__)

Here's the output:

{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}

Here is the link to the question from which my explanation is inspired. Hope it helps someone understand the concept better :)

Amit Yadav
  • 4,422
  • 5
  • 34
  • 79