INHERITANCE
INHERITANCE
Week 6
Information Technology Department
Materials
Computer, Student Activity Sheet, PPT,
elib.ctu.edu.ph
INHERITANCE
References:
Official Python Documentation:
https://docs.python.org/3/tutorial/classes.html#inheritance
Intended Learning Outcomes Real Python: Inheritance and Composition:
https://realpython.com/inheritance-composition-python/
SDG Integration
At the end of the lesson, you should be able to: SDG # 4 – Quality Education (Ensure inclusive and equitable quality
education and promote life-long learning opportunities for all
utilize different types of inheritance in Python SDG # 5 – Gender Equality (Achieve gender equality and empower
all women)
program SDG # 9 – Innovation and Infrastructure (Build resilient
infrastructure, promote inclusive and sustainable industrialization
and foster innovation
Inheritance in Python promotes code reuse by allowing subclasses to inherit methods and attributes from a parent class.
3) Can you give a real-world example of inheritance? How does this concept translate into code?
A real-world example of inheritance is animals. A base class "Animal" defines common traits like "species" and "age." Derived classes
like "Dog" and "Cat" inherit these traits while adding unique behaviors, such as barking or meowing. This structure organizes code
and reflects real-world relationships efficiently.
4) What is the difference between a parent class (or base class) and a child class (or derived class)?
A parent class (base class) provides common attributes and methods, while a child class (derived class) inherits from it and can
add specific features or modify existing ones.
1
Concept Notes Presentation (40 minutes)
Points to Remember
PYTHON INHERITANCE
Inheritance allows a class (child class) to inherit properties and methods from another class (parent class). This helps in
reusability and organizing the code efficiently.
class ParentClass: One class might inherit from another. This relationship is called IS-A, as in, "a Hand is
class Deck: a kind of a Deck".
# Parent class code # Parent class code One class might depend on another in the sense that objects in one class take
objects in the second class as parameters, or use objects in the second class as part
of a computation. This kind of relationship is called a dependency.
class ChildClass(ParentClass):
class Hand (Deck):
# Child class code # Child class code
A class diagram is a graphical representation of these relationships. For example,
Figure 1 shows the relationships between Card, Deck and Hand.
Sample Single Inheritance Python Code: # continuation of Hand class inherits from Deck
def draw(self, num_cards):
# Draw num_cards from the deck and add them to the hand
import random
for _ in range(num_cards):
card = self.deal_card()
# Class to represent a deck of cards. Sample Code 1.
if card:
class Deck:
self.hand_cards.append(card)
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
def show_hand(self):
def __init__(self): return ', '.join([f"{rank} of {suit}" for rank, suit in self.hand_cards])
# Create a full deck of 52 cards
self.cards = [(rank, suit) for suit in Deck.suits for rank in Deck.ranks]
def __repr__(self):
def shuffle(self): return f"Hand with {len(self.hand_cards)} cards"
random.shuffle(self.cards)
# Test the code
def deal_card(self):
return self.cards.pop() if self.cards else None
# Create a deck and shuffle it
def __repr__(self): deck = Deck()
return f"Deck of {len(self.cards)} cards" deck.shuffle()
2
# continuation of Hand class inherits from Deck # What is the output of Sample Code 1?
# Test the code # Write it here!
# Create a deck and shuffle it
deck = Deck()
deck.shuffle()
Deck of 47 cards
# Draw 5 cards from the deck into the hand
hand.draw(5)
Super() Function
The super() function is used to call a method from the parent class inside the child class.
iimport random
class Parent:
def __init__(self, name): # Class to represent a deck of cards. Sample code 2
class Deck:
self.name = name suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
3
Method Overriding
Child classes can override methods from the parent class. Hands-On Activities:
Activity 1: Inheritance and Method Overriding. Sample Code 3
This is useful when the child class has a specific Create a base class Vehicle with attributes like brand and speed. Then create two
implementation for a method already defined in the child classes, Car and Bike, that override a method drive() to display different
messages for each type of vehicle.
parent class.
class Vehicle:
class Parent: def __init__(self, brand, speed):
def greet(self): self.brand = brand
return "Hello from Parent" self.speed = speed
class Bike(Vehicle):
def drive(self):
return f"Bike {self.brand} riding at {self.speed} km/h"
# What is the output of Sample code 3?
# Write it here! # Test your classes
car = Car("Toyota", 120)
bike = Bike("Yamaha", 80)
Car Toyota driving at 120 km/h
Bike Yamaha riding at 80 km/h print(car.drive())
print(bike.drive())
class Athlete:
def __init__(self, sport):
self.sport = sport
def play(self):
return f"Playing {self.sport}"
class Student:
def __init__(self, major):
self.major = major
def study(self):
return f"Studying {self.major}"
4
Guided Practice (30 minutes)
2. Answer the questions on the space provided in the Lesson Preparation above.
3. Recreate the 4 sample codes given in the notes and write the output in the red boxes.
5
Performance
Here are some more fun and creative suggestions for hands-on projects on Python inheritance. Select only one project. Print out the script and sample
output and submit together with the printed notes above with the sample output of the different codes.
1. Zoo Simulator
Create a zoo management system where animals are classified into different species, and each species has its own unique behavior.
Base Class: `Animal` with attributes like `name`, `age`, and `species`.
Child Classes: `Mammal`, `Bird`, `Reptile` with specific behaviors (e.g., `make_sound`, `move`).
- Add special methods for specific animals (e.g., `Lion` roars, `Parrot` can fly, `Turtle` can swim).
- Use inheritance to create subclasses for each specific animal. For example:
- `Lion` (inherits from `Mammal`)
- `Eagle` (inherits from `Bird`)
- `Snake` (inherits from `Reptile`)
Bonus Challenge:
- Implement a feeding schedule based on the type of animal.
- Create an interactive mode where users can “visit” the zoo and see the animals in action.
2. Robot Factory
Build a robot factory that produces different types of robots with unique abilities.
Base Class: `Robot` with common attributes like `model`, `battery_life`, and methods like `charge()` or `shutdown()`.
Child Classes:
- `CleaningRobot`: Can clean a room.
- `SecurityRobot`: Can patrol a room.
- `CookingRobot`: Can prepare a dish.
- The robots should inherit the basic functionality of a robot (e.g., battery life, charging) but override the `work()` method to perform their unique tasks.
Bonus Challenge:
- Introduce a `Malfunction` class that simulates robots running out of battery or breaking down.
- Create a `Factory` class that produces robots dynamically, and students can “order” a specific type of robot.
Base Class: `Superhero` with attributes like `name`, `power_level`, and `health`.
Child Classes: Create different types of superheroes like `FlyingHero`, `StrengthHero`, and `TechHero` with unique abilities. Override the `attack()` method
for each type.
- Each superhero should have a special attack based on their powers (e.g., `FlyingHero` can dive from the sky, `StrengthHero` can punch hard, `TechHero`
can use gadgets).
Bonus Challenge:
- Create a `Villain` class and have superheroes battle them.
- Add power-ups and weaknesses to make the battle more strategic.
Bonus Challenge:
- Implement a `PizzaShop` class that handles multiple orders and generates bills.
- Add special discounts for different types of pizzas or combo deals.
Bonus Challenge:
- Implement a discount system where certain products are on sale or customers can use promo codes.
- Add a `Shipping` class that calculates delivery time and shipping cost based on the product’s weight.
6
class Animal:
def __init__(self, name, age, species):
class Animal:
self.name = name
def __init__(self,
self.age = age name, age, species):
self.name
self.species = name
= species
self.age = age
self.species = species
def make_sound(self):
return "Some sound"
def make_sound(self):
def move(self):
return "Some sound"
return "Moves around"
def move(self):
def __str__(self):
return "Moves around"
return f"{self.name} the {self.species} (Age: {self.age})"
def __str__(self):
return f"{self.name} the {self.species} (Age: {self.age})"
class Mammal(Animal):
def make_sound(self):
return "Generic mammal sound"
class Mammal(Animal):
def def make_sound(self):
move(self):
return
return "Generic
"Walks mammal sound"
on land"
def move(self):
return "Walks on land"
class Bird(Animal):
OUTPUT:
def make_sound(self):
return "Chirp chirp"
class Bird(Animal): Leo the Lion (Age: 5)
Sound: Roar!
def def make_sound(self):
move(self):
Movement: Stalks its prey
return
return "Chirp
"Flies in thechirp"
sky"
Eddie the Eagle (Age: 3)
def move(self): Sound: Screech!
class Reptile(Animal):
return "Flies in the sky" Movement: Soars high in the sky
def make_sound(self):
return "Hiss"
Slippy the Snake (Age: 2)
class Reptile(Animal): Sound: Sssss!
def def
move(self):
make_sound(self): Movement: Slithers on the ground
return "Crawls
return on land"
"Hiss"
def move(self):
class Lion(Mammal):
return "Crawls on land"
def make_sound(self):
return "Roar!"
class
def Lion(Mammal):
move(self):
def make_sound(self):
return "Stalks its prey"
return "Roar!"
def move(self):
class Eagle(Bird):
return "Stalks its prey"
def make_sound(self):
return "Screech!"
class
def Eagle(Bird):
move(self):
return "Soars high in the sky"
def make_sound(self):
return "Screech!"
class Snake(Reptile):
def move(self):
def make_sound(self):
return "Soars high in the sky"
return "Sssss!"
def move(self):
class Snake(Reptile):
return "Slithers on the ground"
def make_sound(self):
return "Sssss!"
def zoo_visit():
def move(self):
animals = [
return "Slithers
Lion("Leo", on the ground"
5, "Lion"),
Eagle("Eddie", 3, "Eagle"),
Snake("Slippy", 2, "Snake"),
] def zoo_visit():
animals = [
Lion("Leo",
for animal 5, "Lion"),
in animals:
Eagle("Eddie", 3, "Eagle"),
print(animal) 7
Snake("Slippy",
print(f"Sound: 2, "Snake"),
{animal.make_sound()}")
]
print(f"Movement: {animal.move()}")
print()
for animal in animals:
print(animal)
if __name__ == "__main__":
print(f"Sound: {animal.make_sound()}")