I am trying to find the right way to use inheritance when the order for the attributes being set for the parent class will break in the child class. Here's an example:
class Car:
def __init__(self, efficiency, tank_size) -> None:
self.efficiency = efficiency
self.tank_size = tank_size
self.range = self.calc_range()
def calc_range(self):
return self.efficiency * self.tank_size
class HybridCar(Car):
def __init__(self, efficiency, tank_size, battery_capacity) -> None:
super().__init__(efficiency, tank_size)
self.battery_range = self.calc_battery_range()
self.battery_capacity = battery_capacity
def calc_range(self):
return self.efficiency * self.tank_size + self.battery_range
def calc_battery_range(self):
return self.battery_capacity * self.efficiency
I would like HybridCar
to call Car
's __init__
method but I can't get it to work. I can't call self.calc_range()
in HybridCar
because I don't have self.battery_range
defined. And I can't define self.battery_range
because that relies on self.efficiency
, which I haven't defined yet. The only way I can see to make this work is for HybridCar not to call Car
's __init__
method but instead have all the same code. I want to avoid this because there's a lot of code in the __init__
method (the real class does much more than this) and seems like bad practice to have lots of duplicated code (And pylint warns me about not calling super().__init__
). What's the right way to solve this?