0% found this document useful (0 votes)
15 views2 pages

Poly Morph 2

Uploaded by

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

Poly Morph 2

Uploaded by

Arkadeep Roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

# Polymorphism example with Shape, Circle, and Rectangle classes

# Base class representing a generic shape


class Shape:
def area(self):
pass # To be overridden by subclasses

# Circle class inheriting from Shape


class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2

# Rectangle class inheriting from Shape


class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width

# Using polymorphism with the common 'area' method


shapes = [Circle(5), Rectangle(4, 6), Circle(3)]

# Calculate the total area of all shapes using the polymorphic 'area' method
total_area = sum(shape.area() for shape in shapes)

# Print the total area


print(f"The total area of all shapes is: {total_area}")

# Special methods example with Point class

# Custom Point class with special methods


class Point:
def __init__(self, x, y):
self.x = x
self.y = y

# Special method '__repr__' returns a string representation.


def __repr__(self):
return f"Point({self.x}, {self.y})"

# Special method '__str__' returns a string representation.


def __str__(self):
return f"({self.x}, {self.y})"

# Special method '__add__' overloads the '+' operator for Vector addition.
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)

# Create instances of the Point class


point1 = Point(1, 2)
point2 = Point(3, 4)

# Demonstrate the use of special methods


print(repr(point1)) # Representation of point1
print(str(point1)) # String representation of point1
print(point1 + point2) # Addition of two points
# Built-in functions and custom data types example with Student class

# Student class representing a student with name and grade


class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade

# Create multiple instances of the Student class


student1 = Student("Alice", 85)
student2 = Student("Bob", 92)
student3 = Student("Charlie", 78)

# Using the custom data type with the built-in filter function
students = [student1, student2, student3]

# Filter students based on the grade using a lambda function


passing_students = list(filter(lambda x: x.grade >= 80, students))

# Print passing students


print("Passing students:")
for student in passing_students:
print(f"{student.name}: {student.grade}")

You might also like