Inheritance
- inheritance – used when the class you’re writing is a specialized version of another class you wrote
- one class inherits from another, it takes on the attributes and methods of the first class
- parent class – original class
- child class – new class, that can inherit attributes and methods from parent class and define new attributes and methods
The __init__() method for a child class
- when writing a new class based on an existing class, call the __init__() method from the parent class
- for example, modeling an electric car, ElectricCar class is based on the Car class
- will only have to write code for the attributes and behaviors specific to electric cars
electric_car.py
class Car:
….”””A simple attempt to represent a car.”””
….def __init__(self, make, model, year):
……..”””Initialize attributes to describe a car.”””
……..self.make = make
……..self.model = model
……..self.year = year
……..self.odometer_reading = 0
….def get_descriptive_name(self):
……..”””Return a neatly formatted descriptive name.”””
……..long_name = f”{self.year} {self.make} {self.model}”
……..return long_name.title()
….def read_odometer(self):
……..”””Print a statement showing the car’s mileage.”””
……..print(f”This car has {self.odometer_reading} miles on it.”)
….def update_odometer(self, mileage):
……..”””Set the odometer reading to the given value.”””
……..if mileage >= self.odometer_reading:
…………self.odometer_reading = mileage
……..else:
…………print(“You can’t roll back an odometer!”)
….def increment_odometer(self, miles):
……..”””Add the given amount to the odometer reading.”””
……..self.odometer_reading += miles
class ElectricCar(Car):
….”””Represent aspects of a car, specific to electric vehicles.”””
….def __init__(self, make, model, year):
……..”Initialize attributes of the parent class.”””
……..super().__init__(make, model, year)
my_leaf = ElectricCar(‘nissan’, ‘leaf’, 2024)
print(my_leaf.get_descriptive_name())
- start with Car
- define the child class, ElectricCar
- __init__ () method takes information required to make a Car instance
- super() function allows you to call a method from the parent class
- super comes from the convention of calling the parent class a superclass and the child class a subclass
- make an instance of the ElectricCar class and assign it to my_leaf
2024 Nissan Leaf
- ElectricCar instance works just like an instance of Car
End of study session.