In this unit, we will delve into three fundamental concepts of Object-Oriented Programming (OOP) - Inheritance, Encapsulation, and Polymorphism - and how they are implemented in Python.
Inheritance is a way of creating a new class using details of an existing class without modifying it. The newly formed class is a derived class (or child class). The existing class is a base class (or parent class).
Python supports several types of inheritance:
Encapsulation is one of the fundamental concepts in OOP. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data.
In Python, we denote private attributes using underscore as the prefix i.e single _
or double __
.
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However we could use the same method to color any shape. This concept is called Polymorphism.
In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class.
Python operators work for built-in classes. But the same operator behaves differently with different types. This feature in Python, that allows the same operator to have different meaning according to the context is called operator overloading.
In Python, we can define a method in such a way that there are multiple ways to call it. This is known as method overloading.
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
By understanding these concepts, you will be able to write more efficient and effective Python code, leveraging the full power of Object-Oriented Programming.