0% found this document useful (0 votes)
2 views31 pages

Week 4 - Inheritance

This document outlines the concept of inheritance in Object-Oriented Programming (OOP), detailing its importance, implementation in Python, and various types of inheritance. It covers key topics such as method overriding, the use of the super() function, and the advantages and disadvantages of inheritance. Additionally, it includes a case study activity for students to design a management system using inheritance principles.

Uploaded by

dominicagutey87
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)
2 views31 pages

Week 4 - Inheritance

This document outlines the concept of inheritance in Object-Oriented Programming (OOP), detailing its importance, implementation in Python, and various types of inheritance. It covers key topics such as method overriding, the use of the super() function, and the advantages and disadvantages of inheritance. Additionally, it includes a case study activity for students to design a management system using inheritance principles.

Uploaded by

dominicagutey87
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

WEEK 4

EL 162 / 234 OBJECT ORIENTED


PROGRAMMING
By: Dr. Matthew Cobbinah

mcobbinah@[Link] | 0547900989
INHERITANCE IN OOP
Learning Objectives
By the end of this lesson, students should be able to:
• Explain the concept of inheritance.
• Describe why inheritance is important in software development.
• Implement inheritance in Python.
• Differentiate between different types of inheritance.
• Understand method overriding.
• Use the super() function correctly.
• Identify advantages and disadvantages of inheritance
Review of Classes and Objects
Class
• A blueprint for creating objects.
class Person:
def __init__(self, name):
[Link] = name
Object
• An instance of a class.
student = Person("John")

Relationship
Class ---------> Object
Blueprint Instance
What is Inheritance?
• Inheritance is an OOP mechanism that allows one class (called
the child or derived class) to acquire the attributes and methods
of another class (called the parent or base class).

• Instead of rewriting existing code, we extend existing classes.

• Mathematically,
Child Class = Parent Class + New Features
Why Do We Need Inheritance?
• Suppose we have three classes:
• Student Without inheritance:
• Lecturer
Student Lecturer Administrator
• Administrator --------- --------- -------------
name name name
• Each has age age age
• Name address address address

• Age Notice the repetition.


• Address

Inheritance eliminates code duplication.


Benefits of Inheritance
• Inheritance promotes:
• Code reuse
• Reduced redundancy
• Easier maintenance
• Better organization
• Extensibility
• Polymorphism support

• Large software systems like banking, hospital management and airline


reservation systems heavily rely on inheritance.
Parent and Child Classes
Parent Class Child Class

Base Class Derived Class

Superclass Subclass

Person

lecturer Student

Person is the parent. Lecturer and Student are children; they inherit from Person
Basic Syntax of Inheritance
• General syntax:
class Parent:
pass

class Child(Parent):
pass

• Notice:
Child(Parent)

The parent class is placed inside parentheses


Example 1 - Simple Inheritance
class Person:
def greet(self):
print(“Good day everyone!")

class Student(Person):
pass
Although Student has no method
s = Student() called greet(), it inherits it from
Person
[Link]()

#Output
Good day everyone!
Example 2 - Inheriting Attributes
class Person:
def __init__(self, name): #constructor
[Link] = name

class Student(Person):
pass
The child class automatically
s = Student(“Matthew") inherits the constructor
print([Link])

#Output
Matthew
Example 3 - Extending a Parent Class
class Person:
def greet(self):
print("Hello")

class Student(Person):
def study(self):
print(“I’m Enjoying the Python OOP Course")

daniella = Student()

[Link]()
[Link]()
#Output
Hello
I’m Enjoying the Python OOP Course A child class can add new methods.
Example 4a - Constructor Inheritance
# Consider:
class Person:
def __init__(self, name):
[Link] = name

# Suppose Student also needs student_id. We write:

class Student(Person):
def __init__(self, name, student_id):
Person.__init__(self, name) # Explicitly call the parent class constructor
self.student_id = student_id

# Test
student = Student("Matthew", "S12345")
print([Link]) # Matthew
print(student.student_id) # S12345
Example 4b - Constructor Inheritance
#Consider:
class Person:
def __init__(self, name):
[Link] = name
#Suppose Student also needs student_id , we write
class Student(Person):
def __init__(self, name, student_id):
super().__init__(name) #Using super() simply automates the process
self.student_id = student_id

# Test
student = Student("Matthew", "S12345")
print([Link]) # Matthew
print(student.student_id) # S12345
The super() built-in function

• super() gives access to the parent class without explicitly


mentioning the class name.
• It returns a temporary object that allows a child class to access the
methods and attributes of its parent class.
super().__init__(name)
Advantages
• Cleaner code
• Supports multiple inheritance
• Easier maintenance
The super() built-in function - Example
class Person:
def __init__(self, name):
[Link] = name

def display(self):
print("Name:", [Link])

class Student(Person):
def __init__(self, name, student_id):
super().__init__(name)
self.student_id = student_id

def info(self):
print("ID:", self.student_id)

student = Student("John", 1001)


#Output
[Link]() Name: John
[Link]() ID: 1001
Method Overriding
• A child class can redefine a method inherited from the parent.
class Animal:
def speak(self):
print("Animal makes a sound")

class Dog(Animal):
def speak(self):
print("Dog barks")
dog = Dog()
[Link]()

#Output
Dog barks The child version overrides the parent version
Calling the Parent Method
class Animal: Sometimes we want both methods
def speak(self):
print("Animal sound")

class Dog(Animal):
def speak(self):
super().speak()
print("Dog barks")
#Output
Animal sound
Dog barks
Types of Inheritance

• Python supports five inheritance types.


1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
Single Inheritance
One parent, One child
Person

Student

class Person:
pass

class Student(Person):
pass
Multiple Inheritance
Teacher

One child, Multiple parents


Student class Student:
pass
TeachingAssistant
class Employee:
pass

class TeachingAssistant(Student, Employee):


pass
Multilevel Inheritance
Person

Student
Inheritance continues across generations.
GraduateStudent class Person:
pass

class Student(Person):
pass

class GraduateStudent(Student):
pass
Hierarchical Inheritance

Person

Student Lecturer Staff

One parent, Many children


Hybrid Inheritance

Combination of inheritance types.


Person

Student Employee

TeachingAssistant
Python supports hybrid inheritance naturally.
Method Resolution Order (MRO)
• When multiple inheritance exists, Python follows the Method Resolution Order
(MRO) to determine which method to invoke.
✓ MRO is the sequence Python follows to determine which method to execute when a class
inherits from multiple parent classes
✓ MRO ensures that Python always knows the correct order in which to search parent classes
for methods and attributes, avoiding ambiguity in multiple inheritance.
• Python uses the C3 Linearization Algorithm to create a consistent, predictable, and
unambiguous order for searching parent classes (resolving methods across complex
inheritance hierarchies)
• You can view a class's MRO using:
[Link]()
or
help(ClassName)
Method Resolution Order (MRO)

class A: #To inspect the MRO:


def show(self):
print([Link]())
print("A")
or
class B(A): help(D)
pass

class C(A):
pass

class D(B, C):


pass
Advantages of Inheritance

• Promotes software reuse


• Simplifies maintenance
• Reduces code duplication
• Encourages modular programming
• Improves scalability
• Supports polymorphism
Disadvantages of Inheritance

• Deep inheritance trees can become difficult to understand.


• Tight coupling between parent and child classes may make changes
risky.
• Incorrect use can violate encapsulation.
• Multiple inheritance increases complexity, especially with conflicting
method names.

Favor composition ("has-a" relationships) over inheritance


("is-a" relationships) when inheritance does not accurately model the
problem domain. Composition is the practice of building complex classes
by combining simpler classes, rather than inheriting from them.
Week 4 — Key Takeaways

1. Inheritance allows a child class to 4. Method overriding enables child


reuse and extend the functionality classes to customize inherited
of a parent class. behavior.

2. The parent class provides common 5. Python supports single, multiple,


attributes and methods, while the child multilevel, hierarchical, and hybrid
class specializes them. inheritance.

3. super() is the recommended way 6. Understanding Method Resolution


to invoke parent class methods and Order (MRO) is essential when working
constructors. with multiple inheritance.
LAB Session
Case Study Activity: UMaT Management System
• UMaT wants to develop a simple system to manage different types of people on campus. All people share
common information such as name and age, but each role has additional responsibilities.
• A Student has a student ID and can enroll in a course.
• A Lecturer has an employee ID and can teach a course.
Requirements:
• Design and implement the following using inheritance:
1. Create a parent class Person with:
✓ Attributes: name, age
✓ Method: display_info()
2. Create child classes:
✓ Student (adds student_id and enroll_course())
✓ Lecturer (adds employee_id and teach_course())
3. Use super() to initialize the inherited attributes.
[Link] one object of each child class and demonstrate that:
✓ They inherit the display_info() method.
✓ They can execute their own unique methods.
5. Override display_info() in one child class to include its unique ID while still displaying the parent's
information using super().
Push your solution to a new GitHub repository named inheritance-umat-management-system. Include
a [Link] introducing the repository and summarizing the task. Add MatthewCobbinah as a
collaborator to the repository.

You might also like