0% found this document useful (0 votes)
5 views

OOPs Python CSE 3216 Module 2 Exam Program

Uploaded by

N.Akshay Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

OOPs Python CSE 3216 Module 2 Exam Program

Uploaded by

N.Akshay Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Module 2: Python Inheritance,

Polymorphism & Exception


Handling

Single Inheritance :

# Single Inheritance Example


class Parent:
def parent_method(self):
print("This is a method from the Parent
class.")
class Child(Parent):
def child_method(self):
print("This is a method from the Child
class.")
# Creating an instance of Child
child_obj = Child()
child_obj.parent_method() # Inherited from
Parent
child_obj.child_method() # Defined in Child
Multiple Inheritance :

# Multiple Inheritance Example


class Father:
def father_method(self):
print("This is a method from Father class.")
class Mother:
def mother_method(self):
print("This is a method from Mother class.")
class Child(Father, Mother):
def child_method(self):
print("This is a method from Child class.")
# Creating an instance of Child
child_obj = Child()
child_obj.father_method() # Inherited from
Father
child_obj.mother_method() # Inherited from
Mother
child_obj.child_method() # Defined in Child
Method Overloading (using
default arguments)
# Method Overloading Example (using
default arguments)
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c

# Creating an instance of Calculator


calc = Calculator()
print(calc.add(5)) # Output: 5 (uses a)
print(calc.add(5, 10)) # Output: 15 (uses a
and b)
print(calc.add(5, 10, 15)) # Output: 30 (uses
a, b, and c)
Method Overriding
# Method Overriding Example
class Parent:
def show(self):
print("This is a method from Parent
class.")

class Child(Parent):
def show(self):
print("This is an overridden method
from Child class.")

# Creating instances
parent_obj = Parent()
child_obj = Child()

parent_obj.show() # Output: This is a


method from Parent class
child_obj.show() # Output: This is an
overridden method from Child class
Method Resolution Order (MRO)
# Method Resolution Order (MRO) Example
class A:
def show(self):
print("Method from class A")
class B(A):
def show(self):
print("Method from class B")
class C(A):
def show(self):
print("Method from class C")
class D(B, C):
pass
# Creating an instance of D
d_obj = D()
d_obj.show() # This will follow the MRO
(Method Resolution Order)
print(D.__mro__) # Shows the MRO

You might also like