top of page

Python Practice Set (Part 11): OOP Inheritance

ree


Building on Blueprints: An Introduction to Python Inheritance


Welcome to Part 11 of our Python practice series! In our last session, we learned how to create "blueprints" for objects using classes. But what if you want to create a new class that is a more specialized version of an existing one? That's where inheritance comes in. Inheritance allows a new "child" class to take on all the attributes and methods of a "parent" class, letting you reuse code and build logical relationships between your objects. Let's explore this powerful OOP principle!


1. The Parent Class: Appliance


First, let's create a general parent class. Create a class named Appliance.

  • The init method should take brand as an argument and store it. It should also initialize an attribute is_onto False.

  • Add a method turn_on() that sets is_on to True and prints a message like "[Brand] has been turned on."

  • Add a method display_status() that prints whether the appliance is on or off.


2. The Child Class: Refrigerator


Now, create a new class called Refrigerator that inherits from the Appliance class. For now, don't add any new methods or attributes to it.

  • Create an instance of Refrigerator, giving it a brand name.

  • Even though you haven't written any code inside Refrigerator yet, you should be able to call the turn_on()and display_status() methods on your new object because it inherited them from Appliance.


3. Adding Child-Specific Methods


A refrigerator does more than just turn on. Add a new method called cool_down() to your Refrigerator class. This method should only work if the refrigerator is_on.

  • Inside cool_down(), check if self.is_on is True.

  • If it is, print "Cooling items..."

  • If it's not, print "Cannot cool down. The refrigerator is off."

  • Test this by creating an instance, turning it on, and then calling cool_down().


4. Overriding a Parent Method


The display_status() method from Appliance is a bit generic. Let's make a more specific version for our Refrigerator. Override the display_status() method in the Refrigerator class.

  • The new method should still print whether the appliance is on or off.

  • Additionally, if the appliance is on, it should also print "Current temperature: 4°C".


5. Extending a Parent Method with super()


Let's create another child class, Microwave, that also inherits from Appliance. We want to override its display_statusmethod too, but without completely replacing the parent's logic.

  • In the Microwave class, override display_status().

  • Inside this new method, first call the parent's version of the method using super().display_status().

  • After that line, add a new line that prints "Current power: 800W". This way, you extend the parent's functionality instead of replacing it.




Comments


bottom of page