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:
In this example:
Animal
is the parent class with a constructor and a methodspeak
.Dog
andCat
are subclasses that inherit fromAnimal
and implement thespeak
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:
In this example:
Bird
is a parent class with an abstract methodfly
.Sparrow
andPenguin
are subclasses that implement thefly
method.- The
bird_flight
function demonstrates polymorphism by accepting any object that is an instance ofBird
and calling thefly
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:
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:
In this example:
Person
is the parent class with an__init__
method and adisplay
method.Student
is a subclass that extendsPerson
by adding astudent_id
attribute.- The
super().__init__(name, age)
call ensures thename
andage
attributes are initialized in thePerson
class. - The
display
method inStudent
calls thedisplay
method inPerson
usingsuper()
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