add another method to Battery that reports the range of the car based on
the battery size:
class Car:
--snip--
class Battery:
--snip--
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 40:
range = 150
elif self.battery_size == 65:
range = 225
print(f"This car can go about {range} miles on a full charge.")
class ElectricCar(Car):
--snip--
my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())
my_leaf.battery.describe_battery()
1 my_leaf.battery.get_range()
The new method get_range() performs some simple analysis. If the bat-
tery’s capacity is 40 kWh, get_range() sets the range to 150 miles, and if the
capacity is 65 kWh, it sets the range to 225 miles. It then reports this value.
When we want to use this method, we again have to call it through the car’s
battery attribute 1.
The output tells us the range of the car based on its battery size:
2024 Nissan Leaf
This car has a 40-kWh battery.
This car can go about 150 miles on a full charge.
Modeling Real-World Objects
As you begin to model more complicated things like electric cars, you’ll
wrestle with interesting questions. Is the range of an electric car a property
of the battery or of the car? If we’re only describing one car, it’s probably
fine to maintain the association of the method get_range() with the Battery
class. But if we’re describing a manufacturer’s entire line of cars, we proba-
bly want to move get_range() to the ElectricCar class. The get_range() method
would still check the battery size before determining the range, but it would
report a range specific to the kind of car it’s associated with. Alternatively,
we could maintain the association of the get_range() method with the bat-
tery but pass it a parameter such as car_model. The get_range() method would
then report a range based on the battery size and car model.
This brings you to an interesting point in your growth as a program-
mer. When you wrestle with questions like these, you’re thinking at a higher
172 Chapter 9