Open up your code editor with the example Ingredient() class that you've built in the previous section. Here's a minimal implementation as an example:
class Ingredient:
"""Models an Ingredient."""
def __init__(self, name, amount):
self.name = name
self.amount = amount
def expire(self):
"""Expires the ingredient item."""
print(f"whoops, these {self.name} went bad...")
self.name = "expired " + self.name
def __str__(self):
return f"You have {self.amount} {self.name}."
How to Create a Python Subclass
Start by creating a new empty class called Spice(). However, instead of really making an empty class, you'll inherit everything from your Ingredient() class:
class Spice(Ingredient):
pass
By adding the name of your parent class into parentheses (()) after your child class' name and before the colon (:), you've successfully inherited everything from your parent class, Ingredient():
p = Ingredient('peas', 12)
print(p) # OUTPUT: You have 12 peas.
s = Spice('salt', 200)
print(s) # OUTPUT: You have 200 salt.
As you may have noticed, the terms "subclass" and "child class" are both used to identify the same thing. Moving forward, you'll see them and hear them being used interchangeably.
As you can see, there's no need to define the class constructor __init__() or the __str__() method again. A Spice() object currently works in just the same way as an Ingredient(). You can also call .expire() on your Spice() object.
Tasks
- Call the
.expire()method on your newSpice()object and confirm that it works as expected.
Summary: Creating a Python Subclass
- Inheritance can inherit all methods and attributes from a parent class
- Putting the parent class in the parentheses of the child class definition will automatically set the inheritance
- This lesson created the
Spiceclass, which inherits fromIngredient