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

Inheritance Programs

The document provides a comprehensive overview of various programming concepts in Python, including inheritance, multiple inheritance, method overriding, polymorphism, operator overloading, and magic methods. It includes multiple example programs demonstrating these concepts, such as the use of base and derived classes, the super() function, method resolution order, and implementing custom behaviors through operator overloading. Each program is designed to illustrate specific features of Python's object-oriented programming capabilities.

Uploaded by

syedaluheena
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Inheritance Programs

The document provides a comprehensive overview of various programming concepts in Python, including inheritance, multiple inheritance, method overriding, polymorphism, operator overloading, and magic methods. It includes multiple example programs demonstrating these concepts, such as the use of base and derived classes, the super() function, method resolution order, and implementing custom behaviors through operator overloading. Each program is designed to illustrate specific features of Python's object-oriented programming capabilities.

Uploaded by

syedaluheena
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Inheritance

Accessing the Inherited Variables and Methods


Program 1: Program to Demonstrate Base and Derived Class Relationship Without Using
__init__() Method in a Derived Class.

class FootBall:
def __init__(self, country, division, no_of_times):
[Link] = country
[Link] = division
self.no_of_times = no_of_times
def fifa(self):
print(f"{[Link]} national football team is placed in '{[Link]}' FIFA division")
class WorldChampions(FootBall):
def world_championship(self):
print(f"{[Link]} national football team is {self.no_of_times} times world champions")
def main():
germany = WorldChampions("Germany", "UEFA", 4)
[Link]()
germany.world_championship()
if __name__ == "__main__":
main()

Output
Germany national football team is placed in 'UEFA' FIFA division
Germany national football team is 4 times world champions

Using super() Function and Overriding Base Class Methods


Program 2: Program to Demonstrate the Use of super() Function.

class Country:
def __init__(self, country_name):
self.country_name = country_name
def country_details(self):
print(f"Happiest Country in the world is {self.country_name}")
class HappiestCountry(Country):
def __init__(self, country_name, continent):
super().__init__(country_name) # calling parent constructor
[Link] = continent
def happy_country_details(self):
print(f"Happiest Country in the world is {self.country_name} and is in {[Link]}")
def main():
finland = HappiestCountry("Finland", "Europe")
finland.happy_country_details()
if __name__ == "__main__":
main()
Output
Happiest Country in the world is Finland and is in Europe

Program 3: Program to Demonstrate the Overriding of the Base Class Method in the Derived
Class.

class Book:
def __init__(self, author, title):
[Link] = author
[Link] = title
def book_info(self):
print(f"{[Link]} is authored by {[Link]}")
class Fiction(Book):
def __init__(self, author, title, publisher):
super().__init__(author, title)
[Link] = publisher
# Overriding parent method
def book_info(self):
print(f"{[Link]} is authored by {[Link]} and published by {[Link]}")
def invoke_base_class_method(self):
super().book_info() # call parent version
def main():
print("Derived Class")
silva_book = Fiction("Daniel Silva", "Prince of Fire", "Berkley")
silva_book.book_info() # calls overridden method
silva_book.invoke_base_class_method() # calls base class method
print("---------------------------------")
print("Base Class")
reacher_book = Book("Lee Child", "One Shot")
reacher_book.book_info()
if __name__ == "__main__":
main()

Output
Derived Class
Prince of Fire is authored by Daniel Silva and published by Berkley
Prince of Fire is authored by Daniel Silva
---------------------------------
Base Class
One Shot is authored by Lee Child

Multiple Inheritances
Program 4: Program to Demonstrate Multiple Inheritance
class Poissonier:

def __init__(self, poissonier_role):


self.poissonier_role = poissonier_role
def display_poissonier_chef_info(self):
print(f"Chef is mainly involved in preparing {self.poissonier_role}")
class Entremetier:
def __init__(self, entremetier_role):
self.entremetier_role = entremetier_role
def display_entremetier_chef_info(self):
print(f"Chef is mainly involved in preparing {self.entremetier_role}")
class Cook(Poissonier, Entremetier):
def __init__(self, poissonier_role, entremetier_role):
Poissonier.__init__(self, poissonier_role)
Entremetier.__init__(self, entremetier_role)
def invoke_base_class_methods(self):
Poissonier.display_poissonier_chef_info(self)
Entremetier.display_entremetier_chef_info(self)
def main():
print(f"Is Cook a derived class of Poissonier Base Class? {issubclass(Cook, (Entremetier, Poissonier))}")
chef = Cook("SeaFood", "Vegetables")
chef.invoke_base_class_methods()
if __name__ == "__main__":
main()

Output
Is Cook a derived class of Poissonier Base Class? True
Chef is mainly involved in preparing SeaFood
Chef is mainly involved in preparing Vegetables

Program 5: Program to Demonstrate Multiple Inheritance with Method Overriding

class Pet:
def __init__(self, breed):
[Link] = breed
def about(self):
print(f"This is {[Link]} breed")
class Insurable:
def __init__(self, amount):
[Link] = amount
def about(self):
print(f"Its insured for an amount of {[Link]}")
class Cat(Pet, Insurable):
def __init__(self, weight, breed, amount):
[Link] = weight
Pet.__init__(self, breed)
Insurable.__init__(self, amount)

def get_weight(self):
print(f"{[Link]} Cat weighs around {[Link]} pounds")
def main():
cat_obj = Cat(15, "Ragdoll", "$100")
cat_obj.about() # calls [Link]() due to method resolution order (MRO)
cat_obj.get_weight()
if __name__ == "__main__":
main()

Output
This is Ragdoll breed
Ragdoll Cat weighs around 15 pounds

Method Resolution Order (MRO)


Program 6: Program to Demonstrate the Construction of Method Resolution Order in Python
Demonstrate Method Resolution Order (MRO)

class First:
def my_method(self):
print("You found me in Class First")
class Second:
def my_method(self):
print("You found me in Class Second")
class Third:
def my_method(self):
print("You found me in Class Third")
class Fourth(Third, First):
pass
class Fifth(Third, Second):
pass
class Sixth(Fifth, Fourth):
pass
def main():
obj = Sixth()
obj.my_method() # resolved using MRO
print([Link]()) # display method resolution order
if __name__ == "__main__":
main()

Program 7: Program to Demonstrate the Solving of Diamond Problem in Python.


class First:
def my_method(self):
print("You found me in Class First")
class Second(First):
pass
class Third(First):
def my_method(self):
print("You found me in Class Third")
class Fourth(Second, Third):
pass
def main():
obj = Fourth()
obj.my_method() # resolved using MRO
print(f"Method Resolution Order is {[Link]()}")
if __name__ == "__main__":
main()

Program 8: Program to Demonstrate the Use of super() Function in Multiple Inheritances

class First:
def __init__(self):
print("In First")
super().__init__()
class Second:
def __init__(self):
print("In Second")
super().__init__()
class Third(First, Second):
def __init__(self):
print("In Third")
super().__init__()
def main():
obj = Third()
print(f"Method Resolution Order is {[Link]()}")
if __name__ == "__main__":
main()

The Polymorphism
Program 9: Program to Demonstrate Polymorphism in Python
class Vehicle:
def __init__(self, model):
[Link] = model
def vehicle_model(self):
print(f"Vehicle Model name is {[Link]}")
class Bike(Vehicle):
def vehicle_model(self):
print(f"Vehicle Model name is {[Link]}")

class Car(Vehicle):
def vehicle_model(self):
print(f"Vehicle Model name is {[Link]}")
class Aeroplane:
pass
def vehicle_info(vehicle_obj):
vehicle_obj.vehicle_model()
def main():
ducati = Bike("Ducati-Scrambler")
beetle = Car("Volkswagon-Beetle")
boeing = Aeroplane()
for each_obj in [ducati, beetle, boeing]:
try:
vehicle_info(each_obj)
except AttributeError:
print("Expected method not present in the object")
if __name__ == "__main__":
main()

Program 10: Write Python Program to Calculate Area and Perimeter of Different Shapes
Using Polymorphism

import math
class Shape:
def area(self):
pass
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height
def area(self):
print(f"Area of Rectangle is {[Link] * [Link]}")
def perimeter(self):
print(f"Perimeter of Rectangle is {2 * ([Link] + [Link])}")

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
print(f"Area of Circle is {[Link] * [Link] ** 2}")

def perimeter(self):
print(f"Perimeter of Circle is {2 * [Link] * [Link]}")
def shape_type(shape_obj):
shape_obj.area()
shape_obj.perimeter()
def main():
rectangle_obj = Rectangle(10, 20)
circle_obj = Circle(10)

for each_obj in [rectangle_obj, circle_obj]:


shape_type(each_obj)

if __name__ == "__main__":
main()

Operator Overloading and Magic Methods


Program 11: Write Python Program to Create a Class Called as Complex and Implement
__add__() Method to Add Two Complex Numbers. Display the Result by Overloading the +
Operator

class Complex:
def __init__(self, real, imaginary):
[Link] = real
[Link] = imaginary

# Overloading + operator
def __add__(self, other):
return Complex(
[Link] + [Link],
[Link] + [Link])

# String representation
def __str__(self):
return f"{[Link]} + i{[Link]}"
def main():
complex_number_1 = Complex(4, 5)
complex_number_2 = Complex(2, 3)
complex_number_sum = complex_number_1 + complex_number_2
print(f"Addition of two complex numbers {complex_number_1} and {complex_number_2} is
{complex_number_sum}")

if __name__ == "__main__":
main()

Program 12: Consider a Rectangle Class and Create Two Rectangle Objects. This Program
Should Check Whether the Area of the First Rectangle is Greater than Second by
Overloading > Operator
class Rectangle:
def __init__(self, width, height):
[Link] = width
[Link] = height
# Overloading > operator
def __gt__(self, other):
rectangle_1_area = [Link] * [Link]
rectangle_2_area = [Link] * [Link]
return rectangle_1_area > rectangle_2_area
def main():
rectangle_1_obj = Rectangle(5, 10)
rectangle_2_obj = Rectangle(3, 4)
if rectangle_1_obj > rectangle_2_obj:
print("Rectangle 1 is greater than Rectangle 2")
else:
print("Rectangle 2 is greater than Rectangle 1")
if __name__ == "__main__":
main()

You might also like