Inheritance and polymorphism are key concepts in object-oriented programming (OOP) that enable code reusability and flexibility. They allow you to create complex systems by defining hierarchical relationships between classes and enabling objects to take on multiple forms.
Inheritance
Inheritance allows a new class (child or subclass) to inherit attributes and methods from an existing class (parent or superclass). This promotes code reuse and establishes a natural hierarchy between classes.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Creating instances of subclasses
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Calling methods on instances
print(dog.speak()) # Output: Buddy says Woof!
print(cat.speak()) # Output: Whiskers says Meow!
In this example:
Animal
is the parent class with a constructor and a method speak
.Dog
and Cat
are subclasses that inherit from Animal
and implement the speak
method.
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common super class. It provides a way to use a single interface to represent different data types or classes.
Example:
class Bird:
def fly(self):
raise NotImplementedError("Subclass must implement this method")
class Sparrow(Bird):
def fly(self):
return "Sparrow flies high!"
class Penguin(Bird):
def fly(self):
return "Penguin can't fly!"
# Function that demonstrates polymorphism
def bird_flight(bird):
print(bird.fly())
# Using polymorphism
sparrow = Sparrow()
penguin = Penguin()
bird_flight(sparrow) # Output: Sparrow flies high!
bird_flight(penguin) # Output: Penguin can't fly!
In this example:
Bird
is a parent class with an abstract method fly
.Sparrow
and Penguin
are subclasses that implement the fly
method.- The
bird_flight
function demonstrates polymorphism by accepting any object that is an instance of Bird
and calling the fly
method.
Method Overriding
Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This is a form of polymorphism.
Example:
class Vehicle:
def move(self):
return "Vehicle is moving"
class Car(Vehicle):
def move(self):
return "Car is driving"
class Boat(Vehicle):
def move(self):
return "Boat is sailing"
# Instances of subclasses
car = Car()
boat = Boat()
# Calling overridden methods
print(car.move()) # Output: Car is driving
print(boat.move()) # Output: Boat is sailing
The super()
Function
The super()
function allows you to call methods from the parent class in a subclass. This is useful for extending or modifying the behavior of inherited methods.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
return f"Name: {self.name}, Age: {self.age}"
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def display(self):
parent_display = super().display()
return f"{parent_display}, Student ID: {self.student_id}"
# Creating an instance of Student
student = Student("Alice", 20, "S12345")
# Calling the overridden method
print(student.display()) # Output: Name: Alice, Age: 20, Student ID: S12345
In this example:
Person
is the parent class with an __init__
method and a display
method.Student
is a subclass that extends Person
by adding a student_id
attribute.- The
super().__init__(name, age)
call ensures the name
and age
attributes are initialized in the Person
class. - The
display
method in Student
calls the display
method in Person
using super()
and extends its functionality.
Summary
- Inheritance: Allows a class to inherit attributes and methods from another class, promoting code reuse and establishing hierarchical relationships.
- Polymorphism: Allows objects of different classes to be treated as objects of a common super class, enabling a single interface to represent different underlying forms.
- Method Overriding: Provides a specific implementation of a method in a subclass that is already defined in its superclass.
super()
Function: Used to call methods from the parent class in a subclass, useful for extending or modifying inherited behavior.
These concepts are fundamental to building modular, reusable, and maintainable code in Python.
Comments
Post a Comment