logo

Switzerland Campus

France Campus

About EIMT

Research

Student Zone


How to Apply

Apply Now

Request Info

Online Payment

Bank Transfer

Object Oriented Programming with Python

Home  /   Object Oriented Programming with Python

Jan 14, 2025

Python is a language that is both flexible and powerful. This makes it an easy programming language to learn to support OOP principles, laying an adequate foundation in bringing them to the programming paradigm and providing developers tools for writing neat, reusable, and maintainable code.

Python is a language that is both flexible and powerful. This makes it an easy programming language to learn to support OOP principles, laying an adequate foundation in bringing them to the programming paradigm and providing developers tools for writing neat, reusable, and maintainable code. That is what it is expected to be with Python. 
We'll dig deep into this blog reading and examine the core concepts of Object-Oriented Programming in Python. We will cover some basic ideas, explain their implementation, and explain how they are used to improve coding practices.

What is Object-Oriented Programming (OOP)?

Object-Oriented Programming (OOP) is a programming paradigm that is based on objects-an instance of a class. The class type gives the blueprint for the object. This blueprint consists of various properties, also known as attributes or fields, and the methods, or functions, that implement certain behaviours. The main goal of OOP is organizing software in a way that imitates reality, such that the code is much easier to understand, maintain, and even to apply new features to.

The foundation of OOP lies in four primary principles:

  • Encapsulation: Concatenation of attributes that involve subject-relevant data and functions intended to change that data. It provides a check on direct access to a few of this subject's parts, which is commonly described as data suppression, hence only achievable through the object's ways can the inside state be altered, both to yield data hiding.
  • Abstraction: The complex inner works of procedures are unveiled, while only the succinct information and most basic things are presented. It permits exploitation on the part of the user as well as distant closeness with objects from a distance, excluding the need to comprehend how mechanics work inside.
  • Inheritance: Inheritance aids in the creation of one class (termed subclass) by incorporating features and methods to another class (termed superclass) enabling good code reuse, such that we have an inheritance relationship between different classes which allows to simplify system structure and reduces redundancy.
  • Polymorphy: Polymorphism means the capability of presenting an interface for different data types. , in the world of OOP, one can argue that any class can use some other classes as long as it is inherited and defined in another class; thus, they don't need identic conduct. This type of polymorphism gives us flexibility in our codebase because it allows us to use the same method name for different behaviours, based on the context.

Classes and Objects in Python:

Everything is an object in Python- it is either data or methods with data. Classes and objects are Python's way of actualizing the OOP principle; literally, classes and objects in Python form containers comprising data (attributes) and methods that use the data. 

In the context of Python, the essence of enclosure data (attributes) and functions (methods) representing life and living organisms created through it in the objects that are a part of this said class. 

Take, for example, the following simple class definition in Python:

class Dog:

    # Initializer / Constructor

    def __init__(self, name, age):

        self.name = name  # Attribute

        self.age = age    # Attribute

 

    # Method

    def bark(self):

        return f"{self.name} is barking!"

 

    def description(self):

        return f"{self.name} is {self.age} years old."

In the example above:

  • A constructor method _ _init_ _ (self, name, age) is used to initialize the state of the object when it is created.
  • self pertains to the instance of the class (or the object).
  • name and age represent the attributes given to the object when it was created.
  • Behaviours that define objects' functionalities are executing an action and elaborating.

Creating an Object:

Once you define a class, you can make objects of that class, or, as we know them, instances of the class, by invoking the class as a function and passing the arguments you need to the constructor.

# Creating an object of the Dog class

my_dog = Dog("Buddy", 5)

 

# Accessing attributes and methods

print(my_dog.name)         # Output: Buddy

print(my_dog.age)          # Output: 5

print(my_dog.bark())       # Output: Buddy is barking!

print(my_dog.description()) # Output: Buddy is 5 years old.

Encapsulation in Python:

One of the supporting principles in object-oriented programming is encapsulation. It is used to limit access to an object's certain parts by bundling data and methods together in order to achieve data integrity.
In Python, encapsulation is a convention which is achieved in most cases through the use of access modifiers.

Python is a language that does not enforce strict constraints concerning access control, but it mandates the use of a naming convention to indicate how attributes and methods can be accessed:

  • Public members: Attributes or methods that are meant for accessing from outside the class. 
  • Protected members: Attributes or methods meant for accessing from within the class or its subclasses. Encoded by a single underscore (_). 
  • Private members: Methods or attributes meant to be used within the class. These are recognizable by a double underscore (__).

Here is an example illustrating encapsulation:

class BankAccount:

    def __init__(self, owner, balance=0):

        self.owner = owner

        self.__balance = balance  # Private attribute

 

    def deposit(self, amount):

        if amount > 0:

            self.__balance += amount

            print(f"Deposited {amount}")

        else:

            print("Deposit amount must be positive.")

 

    def withdraw(self, amount):

        if amount <= self.__balance:

            self.__balance -= amount

            print(f"Withdrew {amount}")

        else:

            print("Insufficient balance!")

 

    def get_balance(self):

        return self.__balance  # Accessor method

Above the code, a class has a private attribute called __balance. To interact with it outside the class, we've used methods like deposit, withdraw, and get _balance.

# Creating a bank account object

account = BankAccount("Alice", 1000)

 

# Accessing public method

account.deposit(500)

 

# Attempting to access private attribute (will raise an error)

# print(account.__balance)  # AttributeError: 'BankAccount' object has no attribute '__balance'

Inheritance in Python:

This mechanism actually enables one class to derive properties and behaviour from another with a great tax of code reuse. It provides for creating family hierarchies of classes. This can be done because Python is an object-oriented language which supports inheritance. Bash into words(has meaning) that you develop base class then consistently build more and more subclasses like stretch and stretch. 
Below is an inheritance example:

class Animal:

    def __init__(self, name):

        self.name = name

 

    def speak(self):

        return "Animal sound"

 

class Dog(Animal):  # Dog class inherits from Animal class

    def __init__(self, name, breed):

        super().__init__(name)  # Calls the __init__ method of the parent class

        self.breed = breed

 

    def speak(self):

        return f"{self.name} barks!"

 

class Cat(Animal):

    def __init__(self, name, color):

        super().__init__(name)

        self.color = color

 

    def speak(self):

        return f"{self.name} meows!"

In the example below both Dog and Cat inherit from the Animal class. Both have access to the name attribute and override the speak method to provide specific behaviours for that specific animal type.

dog = Dog("Buddy", "Golden Retriever")

cat = Cat("Whiskers", "Black")

 

print(dog.speak())  # Output: Buddy barks!

print(cat.speak())  # Output: Whiskers meows!

Polymorphism in Python:

Through polymorphism, different classes have methods with the same name but different behaviour. This means that regardless of what the implemented class is, one is enabled to work through a single interface faster, allowing it to develop more easily and faster.

def animal_speak(animal):

    print(animal.speak())

# Polymorphism in action

animal_speak(dog)  # Output: Buddy barks!

animal_speak(cat)  # Output: Whiskers meows!

Initially built to expect an Animal interface object, passing in a Dog and Cat instance currently, those are then passed to the correct method depending on the type of object.

OOP or  Object Oriented Programming, arguably is the most critical paradigm in all programming due to its cleanliness, re-usability, and maintenance attributes. Python supports OOP exceptionally, and it-handedly allows developers to implement the principles of encapsulation, inheritance, and polymorphism. With Python, the programming of real systems is more intuitive, and it allows serial code to be reduced significantly in classes and objects.