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:
Animalis the parent class with a constructor and a methodspeak.DogandCatare subclasses that inherit fromAnimaland implement thespeakmethod.
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:
Birdis a parent class with an abstract methodfly.SparrowandPenguinare subclasses that implement theflymethod.- The
bird_flightfunction demonstrates polymorphism by accepting any object that is an instance ofBirdand calling theflymethod.
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:
Personis the parent class with an__init__method and adisplaymethod.Studentis a subclass that extendsPersonby adding astudent_idattribute.- The
super().__init__(name, age)call ensures thenameandageattributes are initialized in thePersonclass. - The
displaymethod inStudentcalls thedisplaymethod inPersonusingsuper()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