[go: up one dir, main page]

0% found this document useful (0 votes)
7 views7 pages

INHERITANCE

The document outlines a lesson plan on inheritance in Python, detailing its types, benefits, and practical applications through sample codes and activities. It emphasizes the importance of inheritance in object-oriented programming for code reuse and organization. The document also includes hands-on project suggestions related to inheritance concepts, such as creating a zoo simulator or a robot factory.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

INHERITANCE

The document outlines a lesson plan on inheritance in Python, detailing its types, benefits, and practical applications through sample codes and activities. It emphasizes the importance of inheritance in object-oriented programming for code reuse and organization. The document also includes hands-on project suggestions related to inheritance concepts, such as creating a zoo simulator or a robot factory.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

PC 212 Quantitative Methods

Week 6
Information Technology Department

STUDENT ACTIVITY SHEETS

COLLEGE OF TECHNOLOGY AND ENGINEERING

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

Lesson Preparation/ Review/Preview (15 minutes)


Directions. Answer the following questions.

1) What is inheritance in object-oriented programming, and why is it useful?


Inheritance in object-oriented programming (OOP) allows a subclass to inherit attributes and methods from a superclass. This
promotes code reuse, simplifies maintenance, enables polymorphism, and provides a clear structure for representing relationships
between classes.
2) How does inheritance promote code reuse and reduce redundancy in a Python program?

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.

Basic Syntax of Inheritance


In Python, inheritance is achieved by passing the parent class as a parameter to the child class. The syntax looks like this:

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.

Figure 1. Class diagram.


Types of Inheritance

1. Single Inheritance: A child class inherits from one parent class.


2. Multiple Inheritance: A child class inherits from more than one parent class.
3. Multilevel Inheritance: A child class is derived from another child class, creating a chain.
4. Hierarchical Inheritance: Multiple child classes inherit from one parent class.
5. Hybrid Inheritance: A combination of two or more types of inheritance.

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()

# Hand class inherits from Deck


# Create a hand (which is a type of Deck)
class Hand(Deck):
hand = Hand()
def __init__(self):
super().__init__() # Initialize deck (inherited)
self.hand_cards = [] # Separate list for the hand's cards # Draw 5 cards from the deck into the hand
hand.draw(5)

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()

Hand: 10 of Hearts, Ace of Spades, 3 of


# Create a hand (which is a type of Deck)
hand = Hand()
Diamonds, Jack of Clubs, 7 of Hearts

Deck of 47 cards
# Draw 5 cards from the deck into the hand
hand.draw(5)

# Display the cards in the hand and the remaining deck


print(f"Hand: {hand.show_hand()}") # Shows the 5 cards in hand
print(deck) # Shows the remaining cards in the deck

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']

class Child(Parent): def __init__(self):


def __init__(self, name, age): # Create a full deck of 52 cards
self.cards = [(rank, suit) for suit in Deck.suits for rank in Deck.ranks]
super().__init__(name) # Call the parent
def shuffle(self):
constructor random.shuffle(self.cards)
self.age = age
def deal_card(self):
return self.cards.pop() if self.cards else None
child = Child("Pio", 12)
def __repr__(self):
print(child.name) # Output: Pio return f"Deck of {len(self.cards)} cards"
print(child.age) # Output: 12
# Hand class inherits from Deck
class Hand(Deck):
def __init__(self):
super() in __init__(): super().__init__() # Call the parent class (Deck) constructor
self.hand_cards = [] # Separate list for the hand's cards

In the Hand class, super().__init__() is used to call def draw(self, num_cards):


# Draw num_cards from the deck and add them to the hand
the constructor of the parent class Deck, so that for _ in range(num_cards):
the Hand object is initialized with a deck of cards. card = self.deal_card()
if card:
self.hand_cards.append(card)
Calling Parent Class Methods: def show_hand(self):
The Hand class uses methods (deal_card() and return ', '.join([f"{rank} of {suit}" for rank, suit in self.hand_cards])

shuffle()) inherited from the Deck class, which def __repr__(self):


were initialized using super(). return f"Hand with {len(self.hand_cards)} cards"

# Test the code

# Create a deck and shuffle it


deck = Deck()
# What is the outp ut of Sample code 2?
deck.shuffle()
# Write it here!
hand = Hand()
Hand: 10 of Hearts, Ace of Spades, 3 of Diamonds,
Jack of Clubs, 7 of Hearts hand.draw(5)

# Display the cards in the hand and the remaining deck


Deck of 47 cards print(f"Hand: {hand.show_hand()}") # Shows the 5 cards in hand
print(deck) # Shows the remaining cards in the deck

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 Child(Parent): def drive(self):


def greet(self): return "Driving at speed"
return "Hello from Child"
class Car(Vehicle):
c = Child() def drive(self):
print(c.greet()) # Output: Hello from Child return f"Car {self.brand} driving at {self.speed} km/h"

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())

Implementing Multiple Inheritance. Sample Code 4


Create two parent classes: Athlete and Student. Create a child
class StudentAthlete that inherits from both. Demonstrate how
methods from both parents are available to the child.

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

class StudentAthlete(Athlete, Student):


def __init__(self, sport, major):
Athlete.__init__(self, sport)
Student.__init__(self, major)

# What is the outp ut of Sample code 4?


# Test your class
# Write it here!
student_athlete = StudentAthlete("Basketball", "Computer
Science")
Playing Basketball
Studying Computer Science
print(student_athlete.play())
print(student_athlete.study())

4
Guided Practice (30 minutes)

1. Printout the notes given above.

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.

4. Perform the hands-on project in the Perfomance below.

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.

3. Superhero Battle Simulator


Let students create their own superheroes and simulate battles between them.

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.

4. Pizza Ordering System


Develop a pizza ordering system where customers can customize and order pizzas.
Base Class**: `Pizza` with basic attributes like `size` and `crust_type`.
Child Classes: - `VegetarianPizza`, `MeatLoversPizza`, `CheesePizza`, each with predefined ingredients.
- Each subclass should override the `describe_pizza()` method to list the ingredients.
- Customer Class**: Customers can order and customize their pizza (choose extra toppings, remove ingredients, etc.).

Bonus Challenge:
- Implement a `PizzaShop` class that handles multiple orders and generates bills.
- Add special discounts for different types of pizzas or combo deals.

5. Online Storefront System


Create an online storefront where users can browse products, add them to a shopping cart, and check out.
Base Class**: `Product` with attributes like `name`, `price`, and `category`.
Child Classes:
- `Electronics`, `Clothing`, `Food`, each with additional details specific to the product type (e.g., electronics have a warranty, food has an expiration date).
-Customer Class**: Customers can browse products, add items to their cart, and complete a purchase.

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()}")

You might also like