Skip to content

Commit 1cca375

Browse files
committed
class composition
1 parent f8f8035 commit 1cca375

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

10. classes/6. composition.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,51 @@ def upgrade_battery(self, new):
8282
else:
8383
self.battery_size = new
8484

85+
class ElectricCar(car):
86+
87+
def __init__(self, make, model, year):
88+
89+
''' Calling init from the parent class, which initializes attributes'''
90+
super().__init__(make, model, year)
91+
self.battery = Battery() #! see docstring 1 below
92+
93+
# def describe_battery(self):
94+
# print(f"\nThis battery has {self.battery_size}-KWh battery")
95+
96+
my_ecar = ElectricCar('nissan', 'leaf', 2024)
97+
print(my_ecar.descriptive_name())
98+
99+
my_ecar.battery.describe_battery()
100+
my_ecar.battery.get_range()
101+
102+
103+
104+
""" In the ElectricCar class, we now add an attribute called self.battery 3.
105+
This line tells Python to create a new instance of Battery (with a default size
106+
of 40, because we're not specifying a value) and assign that instance to the
107+
attribute self.battery. This will happen every time the __init__() method
108+
is called; any ElectricCar instance will now have a Battery instance created
109+
automatically.
110+
We create an electric car and assign it to the variable my_leaf. When
111+
we want to describe the battery, we need to work through the car's battery
112+
attribute
113+
"""
114+
115+
#! i can also make Battery object for dynamic battery size
116+
117+
battery_obj = Battery(50)
118+
battery_obj.describe_battery()
119+
battery_obj.get_range()
120+
121+
122+
# Battery Upgrade: Use the final version of electric_car.py from this section.
123+
# Add a method to the Battery class called upgrade_battery(). This method
124+
# should check the battery size and set the capacity to 65 if it isn’t already.
125+
# Make an electric car with a default battery size, call get_range() once, and then
126+
# call get_range() a second time after upgrading the battery. You should see an
127+
# increase in the car’s range.
128+
129+
print(f"\nafter upgrading the battery:")
130+
print(f"---------------------------------")
131+
my_ecar.battery.upgrade_battery(60)
132+
my_ecar.battery.get_range()

0 commit comments

Comments
 (0)