6.3. Object-Oriented Programming in Python: Inheritance and Polymorphism
Object-oriented programming (OOP) is a programming paradigm that provides a way to structure programs so that properties and behaviors are grouped into individual objects. Python is an object-oriented programming language and this will be the focus of our discussion in this chapter, focusing on inheritance and polymorphism.
Inheritance in Python
Inheritance is a fundamental OOP concept that allows you to create a new class that is a modified version of an existing class. The original class is called the base class or parent class, and the new class is called the derived class or child class. The child class inherits all the attributes and behaviors of the parent class, but can also add new ones or modify existing ones.
In Python, inheritance is declared by passing the parent class as a parameter to the child class. Here is an example:
classAnimal: def __init__(self, name): self.name = name class Dog(Animal): def bark(self): return "Woof!"
In the example above, the Dog class inherits from the Animal class. This means that a Dog object has a name attribute and a bark() method.
Polymorphism in Python
Polymorphism is another fundamental OOP concept that refers to the ability of an object to take on many forms. In Python, polymorphism is implemented in two ways: method overloading and method overriding.
Method overloading refers to the ability of a class to have multiple methods with the same name but different parameters. In Python, method overloading is performed using default arguments or variable arguments.
Here is an example of method overloading in Python:
class Rectangle: def area(self, length=1, breadth=1): return length * breadth
In the example above, the area() method can be called with zero, one or two arguments.
Method overriding refers to the ability of a child class to change the implementation of a method that it inherited from its parent class. This is done simply by declaring a method in the child class with the same name as the method in the parent class.
Here is an example of method overriding in Python:
classAnimal: def sound(self): return "Generic animal sound" class Dog(Animal): def sound(self): return "Woof!"
In the example above, the Dog class replaces the sound() method of the Animal class.
In summary, object-oriented programming in Python, with the use of inheritance and polymorphism, allows you to create code that is flexible and reusable. Inheritance allows you to create new classes from existing classes, and polymorphism allows objects from different classes to be treated in the same way. These concepts are fundamental to creating complex software and are an essential part of any Python course.