Inheritance lets a subclass receive attributes and methods defined by a parent, then add or change behavior. It fits a stable “is-a” relationship: Food is a Product, and Drink is a Product. The parent holds genuinely shared features; subclasses describe differences and avoid duplication.
In everyday terms, a Vehicle may provide a brand and movement behavior; a Bicycle adds pedals and a Car adds an engine. Inheritance does not copy a parent object. It establishes a type relationship: Python looks for a method on the subclass first, then follows the inheritance chain to its parent.
Parent construction and subclass extension
Inheritance assembly line: parent features flow into subclasses
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
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
class Drink(Product):
def __init__(self, name, price, size):
super().__init__(name, price)
self.__size = sizeKNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Overriding and method lookup
A subclass overrides a method by defining the same method name as its parent. For food.__str__(), Python chooses Food's version first. That override may still call super().__str__(), which is useful for keeping the common result and adding detail.
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)Burger object kitchen: parent recipe plus subclass ingredients
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Make EBook inherit Product
- Product stores name and price.
- EBook(Product) adds file_size.
- Use super().__init__ for shared fields.
- Print all three fields.
Override a notification method
- Notification.send() returns a generic message.
- EmailNotification and SMSNotification inherit it.
- Override send() with channel-specific output.
- Create and call one object of each type.
Extend the restaurant menu model
- Create Product(name, price) and __str__.
- Food adds calories; Drink adds size.
- Both call super().__init__ and override __str__.
- Create at least two Food and two Drink objects and print each.