3) Inheritance Lesson

Example Ingredient Python Class

5 min to complete · By Martin Breuss

In the previous two sections, you learned about object-oriented programming in Python.

OOP Main Concepts

You've encountered practical examples of the tenets of OOP:

  1. Abstraction creates a black box that shows only what's necessary for a user-friendly interface.
  2. Encapsulation binds data and logic together, exposing a public interface and hiding other parts.
  3. Inheritance allows classes to pass on their attributes and methods to child classes.
  4. Polymorphism gives the possibility for different classes to implement the same attributes and methods but handle their logic differently.
  5. Composition allows you to compose an object ("composite") of one or more smaller objects ("components"), each of which represents a part of the whole. Composition allows an object to be defined through what it has rather than what it is, and it allows larger objects to be built from smaller objects.

Ingredient Csass

You've built an Ingredient() class and a child class to it, Spice(). While doing so, you've covered the following concepts:

  • Creating classes
  • Creating instances of a class
  • Instance variables
  • Methods
  • Dunder Methods, such as __init__() and __str__()
  • Creating child classes through inheritance
  • Extending the functionality of a child class
  • Overriding methods and dunder methods
  • Composing a composite class from multiple component classes

If you built out the example code, you should have something similar to the code shown below. Read over the code and try to identify where you're applying the tenets of OOP, and voice to yourself what is happening in this code block:

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}."


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

    def __init__(self, name, amount, taste):
        super().__init__(name, amount)
        self.taste = taste

    def expire(self):
        print(f"your {self.name} has expired. it's probably still good.")
        self.name = "old " + self.name

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


c = Ingredient("carrots", 2)
p = Spice("pepper", 2, "hot")
p.expire()
print(c, p)

You can also take out your notebook and transcribe the code. Maybe you want to make an annotated code snippet that you can hang on your fridge, you know, right next to all those spices and ingredients :)

Illustration of a lighthouse

Tasks

  • Play with the code in your text editor. Create objects, call methods on them, and print out their values.
  • Practice using your debugging skills to inspect the attributes of your objects at different times in your code.
  • Extend the functionality of your classes if you haven't yet. Add more methods and more attributes.
  • Add a second child class if you haven't yet. What else do you need for cooking that could be a child class of either of the two existing classes?

In the next lessons, you'll find instructions to apply your learning about OOP in Python to more practical projects.

Summary: Ingredient Example Python Class

  • This lesson provides the final Ingredient class code example with the Spice subclass
  • This lesson also contains a review of abstraction, encapsulation, inheritance, polymorphism and composition