8.2 Inheritance and Overriding
Inheritance lets one class receive attributes and methods from another class. It is useful for “is a” relationships: Food is a Product, and Drink is also a Product.
Inheritance
The parent class stores shared features, and subclasses add differences.
Loading interactive lab...
python
class Product:
def __init__(self, name, price):
self.__name = name
self.__price = price
def get_name(self):
return self.__name
def get_price(self):
return self.__price
class Food(Product):
def __init__(self, name, price, calories):
super().__init__(name, price)
self.__calories = calories
def get_calories(self):
return self.__calories
class Drink(Product):
def __init__(self, name, price, size):
super().__init__(name, price)
self.__size = size
def get_size(self):
return self.__sizesuper().__init__(name, price) calls the parent constructor so shared name and price are initialized first.
Loading concept check...
Overriding
When a subclass needs to change inherited behavior, it can override a method. A common example is overriding __str__().
Loading interactive lab...
python
class Product:
def __init__(self, name, price):
self.__name = name
self.__price = price
def __str__(self):
return "%s ($%.2f)" % (self.__name, self.__price)
class Food(Product):
def __init__(self, name, price, calories):
super().__init__(name, price)
self.__calories = calories
def __str__(self):
return "Food: %s, %d Kcal" % (super().__str__(), self.__calories)
food = Food("Cheeseburger", 5.45, 302)
print(food)Output:
text
Food: Cheeseburger ($5.45), 302 KcalThe subclass __str__() can call super().__str__() to reuse the parent string format.
Loading concept check...
Reusing Parent Logic While Overriding
Overriding does not always mean throwing away the parent code. Often, a subclass wants to add information before or after the parent result, so the overridden method calls super().
python
def __str__(self):
return "Food: %s, %d Kcal" % (super().__str__(), self.__calories)Loading concept check...
Loading practice...