3) Inheritance Lesson

Adding Functionality to Python Subclasses

3 min to complete · By Martin Breuss

Child classes can do more than just copy their parents. They can define new methods and attributes that their parent classes don't have and even change how the attributes and methods that they inherited behave.

Create a Subclass Method

In this lesson, you'll add a new method called .grind() to your Spice() class. You want to be able to grind your spices, but you don't want to grind any other Ingredient(). Your instances of the Spice() class will be everything that an Ingredient() is, with the added functionality to .grind() them:

class Spice(Ingredient):
    """Models a spice to flavor your food."""

    def grind(self):
        print(f"You have now {self.amount} of ground {self.name}.")

Call the Method

After adding this new method to your child class, you can now .grind() spices, while you can't grind other Ingredient() objects:

c = Ingredient('carrots', 3)
p = Spice('pepper', 20)

p.grind()  # OUTPUT: You have now 20 of ground pepper.
c.grind()  # OUTPUT: AttributeError: 'Ingredient' object has no attribute 'grind'

In this code example, you wrote a new .grind() method that is unique to your child class Spice() and that doesn't exist in its parent class, Ingredient().

Subclass Method in Parent Class

You could successfully call the method on a Spice() object, but when attempting to call it on an Ingredient() object, Python presented you with an AttributeError.

As you can see, Python is always trying to be helpful and descriptive. It points you in the right direction even when you're working with your own custom classes and methods.

Illustration of a lighthouse

Tasks

  • Implement another method that is specific to your Spice() class. What else could be useful for a spice?
  • Confirm that it works as expected and that your new method is available to Spice() objects but not to Ingredient() objects.

Coming up, you'll learn how you can change the functionality of methods of the parent class in your child class.

Summary: Python Subclass New Functionality

  • New methods can be added to child classes
  • Adding methods extends the functionality of the child class from the parent
  • Methods are added in child classes in the standard way