I am getting error in this simple piece of code while using super function

I have tried changing the code a little but it didn't work. Here's the code anyway.

class Car:
    def __init__(self,model,name,year):
        self.name=name
        self.model=model
        self.year=year
        self.Class='normal'
        self.odometer=0
    def descriptive_name(self):
        return f'{self.year} {self.name} {self.model}'
    def type(self):
        return self.Class
    def odometer_reading(self):
        return self.odometer

class Battery:
    def __init__(self):
        self.capacity='75 kwh'
    def get_capacity(self):
        return self.capacity

class Electric_car:
    def __init__(self,model,name,year):
        super(Car()).__init__(model,name,year)
        self.battery=Battery()
        self.Class='Electric_car'
    def my_battrey(self):
        return self.battery.get_capacity()

The code above is in the same directory as the code below. Name the code above as main.py and in the same directory write the code below in new file and try running it.

import main
my_scorpio=main.Car('s','scorpio',2019)
print(my_scorpio.descriptive_name())
print(my_scorpio.odometer_reading())
print(my_scorpio.type())
my_tesla=main.Electric_car('s','Tesla',2019)
print(my_tesla.descriptive_name())
print(my_tesla.odometer_reading)
print(my_tesla.type())
print(my_tesla.my_battrey())

2 answers

  • answered 2021-04-21 10:25 edoput

    class Electric_car:
        def __init__(self,model,name,year):
            super(Car()).__init__(model,name,year)
    

    I would guess from your title that this is the issue at hand.

    In python you have to say explicitly that ElectricCar inherits from Car using this syntax

    class Electric_car(Car):
        def __init__(self,model,name,year):
            # this will give you the bound super object
            # from the inheritance Car > ElectricCar
            super(Car, self).__init__(model,name,year)
    

    Then using super(Car, self) would know where to look for in the inheritance tree.

    As pointed out in the comments you could also go for super(ElectricCar, self) as it is true that isinstance(self, ElectricCar).

    The error here was not setting up the inheritance tree by specifying that the ElectricCar is a subclass of a Car and therefore you can't get that far!

    Without the inheritance bit then isinstance(self, Car) would be false as self is of type ElectricCar which does not inherit from Car!

    I really suggest reading the documentation for super though because it explains what is happening when you use it!

  • answered 2021-04-21 10:26 XtianP

    The right way (old style) to call super is:

    super(Electric_car, self).__init__(model,name,year)
    

    Or simply (in Python 3.x):

    super().__init__(model,name,year)