len
function works differently based on the object type:# Printing length of different objects
print(len([2, 4, 6, 8, 9])) # Output: 5
print(len("FACE Prep")) # Output: 9
Here, the len
method calculates the length of a list and a string, demonstrating polymorphism in action.calculate_area
method is defined differently in two classes:class Rectangle:
length = 5
breadth = 3
def calculate_area(self):
return self.length * self.breadth
class Circle:
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
# Creating objects
rec = Rectangle()
cir = Circle()
# Accessing the method
print("Area of a rectangle:", rec.calculate_area()) # Output: 15
print("Area of a circle:", cir.calculate_area()) # Output: 50.24
Here, the method calculate_area
works differently depending on the class it belongs to, showcasing polymorphism.# Parent class
class Car:
def drive(self):
print("I can drive at a speed of 60km/hr")
# Child class
class RaceCar(Car):
def drive(self):
print("I can drive at a speed of 140km/hr")
# Creating objects
car = Car()
race_car = RaceCar()
# Accessing the method
car.drive() # Output: I can drive at a speed of 60km/hr
race_car.drive() # Output: I can drive at a speed of 140km/hr
In this example, the drive
method is overridden in the RaceCar
class, and its behavior changes accordingly.read
and write
can handle different file formats (e.g., text, binary, JSON).