Search code examples
pythonpython-3.xclassattributessuper

'child class' object has no attribute 'attribute_name'


I can not retrieve the value of a variable created only by the inherited child class. Also, changing the value of a variable inherited from the parent class in the init of the child class does not apply.

Here's the parent class:

class Car():

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)

    def get_descriptive_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")

    def increment_odometer(self, miles):
        self.odometer_reading += miles

And here's the child class:

class ElectricCar(Car):

    def __init___(self, make, model, year):
        super(ElectricCar, self).__init__(make, model, year)
        self.odometer_reading = 100
        self.battery_size = 70

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)

    def describe_battery(self):
        print(self.battery_size)

Now, if I try to run this code:

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla)
print(my_tesla.describe_battery())

I get the following exception:

<class '__main__.ElectricCar'>:
{'make': 'tesla', 'model': 'model s', 'year': 2016, 'odometer_reading': 0}

AttributeError: 'ElectricCar' object has no attribute 'battery_size'

I have an oddmeter_reading variable whose value is 0 in the parent class. I changed from child class to 100, but it did not apply. Also, the variable battery_size, which is set only in the child class, is not created in init.

What's the problem? What am I missing?


Solution

  • There is a typo in your ElectricCar class. You defined the method __init___ with 3 underscores instead of two, so it is not being called when you make a new instance.

    If you change your ElectricCar class to this:

    class ElectricCar(Car):
    
        def __init__(self, make, model, year): #Note the two underscores
            super(ElectricCar, self).__init__(make, model, year)
            self.odometer_reading = 100
            self.battery_size = 70
    
        def __str__(self):
            return str(self.__class__) + ": " + str(self.__dict__)
    
        def describe_battery(self):
            print(self.battery_size)
    

    then this will be the output:

    <class '__main__.ElectricCar'>: {'make': 'tesla', 'model': 'model s', 'year': 2016, 
    'odometer_reading': 100, 'battery_size': 70}
    70
    None