OOP is a programming paradigm that organizes code around objects rather than functions and procedures.
These objects represent real-world entities and have:
OOP allows you to:
It is widely used in many programming languages, including Python, to develop complex and scalable applications.
Let’s model a person:
Methods can modify attributes
The grow_older() method will increase the person’s age by 1.
The learn(“Python”) method will add “Python” to the list of skills.
Encapsulation consists of grouping data and the methods that manipulate it within the same object.
It allows you to:
Inheritance allows new classes to be created from existing classes by inheriting their attributes and methods. This promotes:
Example: Square inherits from Rectangle. A square is a rectangle with additional properties.
Polymorphism allows objects from different classes to respond differently to the same action.
It allows objects from different classes to be manipulated uniformly by using common interfaces.
class Person:
def __init__(self, last_name, first_name, age):
self.last_name = last_name
self.first_name = first_name
self.age = age
self.skills = []
def learn(self, new_skill):
"""Adds a new skill to the list of skills."""
self.skills.append(new_skill)
def grow_older(self):
"""Increments the person's age by one year."""
self.age += 1From the Person class, we can create objects.
The code Person("Touille", "Sacha", 20) calls the __init__() method of the Person class.
This method is called the constructor.
As its name suggests, it is used to “build” objects from the class.
_)One of the three pillars of OOP is inheritance.
A child class can use all the attributes and methods of its parent class.
This inheritance principle also allows common attributes and methods to be shared in order to avoid code duplication.
Suppose that in our code, we want to manage bicycles and scooters.
The naive idea is to create a class for each one.
class Bike:
def __init__(self, color, nb_gears):
self.color = color
self.nb_gears = nb_gears
self.speed = 0 # Initial speed is 0
def accelerate(self, increment):
"""Increases the bike speed."""
self.speed += increment
def slow_down(self, decrement):
"""Decreases the bike speed."""
self.speed -= decrement
if self.speed < 0:
self.speed = 0 # Speed cannot be negativeclass Scooter:
def __init__(self, color):
self.color = color
self.speed = 0 # Initial speed is 0
def accelerate(self, increment):
"""Increases the speed."""
self.speed += increment
def slow_down(self, decrement):
"""Decreases the speed."""
self.speed -= decrement
if self.speed < 0:
self.speed = 0 # Speed cannot be negativeThinking about it, we realize that these two classes have common attributes and methods:
One idea is to group these common characteristics into a TwoWheels class. Then make Bike and Scooter inherit from TwoWheels.
class TwoWheels:
def __init__(self, color):
self.color = color
self.speed = 0 # Initial speed is 0
def accelerate(self, increment):
"""Increases the speed."""
self.speed += increment
def slow_down(self, decrement):
"""Decreases the speed."""
self.speed -= decrement
if self.speed < 0:
self.speed = 0 # Speed cannot be negativeself is a reference to the current instance of the class
super() is a built-in function that references the parent class
Draw me a two-wheeler
If you are asked to draw a two-wheeler, you do not really know how to do it because you lack information.
Whereas drawing a bicycle or a scooter is much more concrete.
Some classes are not intended to be instantiated. For example, we will not create objects from the TwoWheels class.
We will directly create Bikes and Scooters.
Therefore, we can define the TwoWheels class as abstract.
The main purpose of abstract classes is to define a contract for child classes.
They provide a consistent structure and organization for classes that share common characteristics, while allowing flexibility for specific implementations in each child class.
Tip
In Python, the concept of abstract classes is implemented using the abc module (Abstract Base Classes).
This module provides the @abstractmethod decorator, which allows a method to be declared as abstract in an abstract class.
An abstract class is defined by inheriting from the ABC class of the abc module.
Warning
A parent class does not necessarily mean an abstract class.
For example:
Consider a ElectricBike class that inherits from the Bike class
This seems logical because an electric bike is a bike
However, in this case, the Bike class does not need to be abstract because creating a bike object is perfectly valid