Understanding Object-Oriented Programming in Python 

In this article we are going to cover Understanding Object-Oriented Programming in Python.

Abstract

Object-oriented programming or OOP is a programming approach or paradigm in which emphasis is laid on organizing a program based on its data. It uses objects and classes to make it closer to resembling real-world entities. It strives to emphasize data and security and code reusability. Using OOPs in Python, more effective and efficient programming can be achieved. The main concepts of object-oriented programming in Python are- inheritance, polymorphism, encapsulation, and abstraction. 

Scope

  • This article deals with understanding object-oriented programming in Python in brief. 
  • We will also comprehend them with the help of examples.

Introduction

As programmers, we deal with code as a part of our work. But, a few of the important factors that need to be taken into consideration include data and security. This can be taken care of by using object-oriented programming. Python is one of the most popular object-oriented programming languages. 

Object-oriented programming or OOP is a programming approach or paradigm in which emphasis is laid on organizing a program based on its data. It uses objects and classes to make it closer to resembling real-world entities. It strives to emphasize data and security and code reusability. Using OOPs in Python, more effective and efficient programming can be achieved. Also, OOP is an important concept for developers who wish to develop applications with advanced security and flexibility. 

Importance of Object-Oriented Programming in Python 

Object-oriented programming in Python plays a very important role. The main aim was to overcome the drawbacks of procedural-oriented programming. By using OOPs, developers can create programs that can incorporate the following-

  • Code-reusability– By using object-oriented programming, code reusability is possible that eventually saves time and effort.
  • Security– The security of the software can be improved by using many features like abstraction, design patterns, etc. 
  • Modularity– Modularity can be introduced by OOP which aims at making it easy to maintain the code. It is also meant to ensure that the changes made to one part do not affect the other. 
  • Resemblance to the real-world– Object-oriented programming can make our code resemble real-world entities by using objects and classes. 

Main concepts of object-oriented programming in Python

The main concepts of object-oriented programming in Python include-

  • Objects
  • Classes
  • Abstraction
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Cohesion
  • Coupling
  • Aggregation
  • Composition

The above are the main concepts of object-oriented programming in Python which play an important role. 

Four Pillars of OOPs in Python

The fundamental principles of object-oriented programming in Java are-

  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

These principles serve as the foundation of OOP and are crucial for creating efficient and scalable code. A simple way to remember these principles is through the mnemonic “I ate A PIE,” representing the first letter of each principle.

Class in Python

Class in Python is defined as the collection or blueprint of similar kinds of objects. It is also known as the “Blueprint of an object”. It is used to create objects that have certain attributes and methods associated with them. We need to use the ‘class’ keyword to create a class. A class is a user-defined data type. It does not occupy memory. The variables that belong to the class are known as ‘attributes’. The attributes can be accessed using the ‘.’ dot notation.

Syntax:
class className:
..#set of statements
..

Objects in Python

As the name Object-oriented programming suggests, objects are the fundamental concepts of OOPs on which the foundation is laid. Objects are entities that contain attributes like state and behaviour associated with it. Objects are also known as the ‘instance of the class’. They are real-world entities. Objects consist of- 

  • State- The attributes of the object represent the state. 
  • Behaviour- The methods of the object represent the behaviour. 
  • Identity- It is used to uniquely identify each object. 

In order to understand the above concepts, let us take the example of a cat which is considered an object.

  • State- The fur colour, eye colour, size, breed etc. can be considered as the state of the cat which represents the attributes.
  • Behaviour- The action of the cat like eating, sleeping etc. can be considered as its behaviour.
  • Identity- The name of the cat is its identity. 

Unlike class, objects contain memory. Message passing is the process by which objects interact with each other and share messages. 

Example for class and object in Python

In the example, we have created a class called Cat and defined attributes within the class. Then we created objects of the class and set the values of the attributes. 

class Cat:
    #attribute
    gender = ""
    age = 0

# create a first object
cat1 = Cat()
cat1.gender = "F"
cat1.age = 8

# create another object 
cat2 = Cat()
cat2.gender = "M"
cat2.age = 2

# access the required attributes
print(f"The gender is {cat1.gender} and age {cat1.age} years")
print(f"The gender is {cat2.gender} and age {cat2.age} years")

Output:

The gender is F and age 8 years 
The gender is M and age 2 years

The self

The self is a reference to the instance of the class. When you create an instance of a class, you can call methods and access attributes of that instance using the self parameter. self is a convention and not a reserved keyword in Python. However, it is common to use self as the first parameter of instance methods.

Abstraction in Python

Abstraction means hiding the implementation details and only showing the essential information. The main purpose is to show only the details that are required and hide unnecessary information. This is done to ease the process for the user. In Python, abstraction is achieved through objects and classes. We can also use abstract classes and interfaces to achieve the same. It makes the code secure as we are not revealing the implementation details. 

Example-

from abc import ABC, abstractmethod

class Phone(ABC):

    @abstractmethod
    def ring(self):
        pass

class iPhone(Phone):

    def ring(self):
        print("iPhone ringing")

class Samsung(Phone):

    def ring(self):
        print("Samsung ringing")

# create objects
iphone = iPhone()
samsung = Samsung()

# call the ring method on objects
iphone.ring()  
samsung.ring()  

Output:

iPhone ringing
Samsung ringing

So, when we use “from abc import ABC, abstractmethod”, we are importing the ABC class and the abstractmethod decorator from the abc module. We can use these to define our own abstract classes and abstract methods. In this example, the Phone class defines an abstract ring() method that all phone classes must implement. The iPhone and Samsung classes inherit from Phone class and implement their own ring() methods that print out different messages. 

Inheritance in Python

Inheritance is the process by which one class can be derived from other classes. One class can inherit the features of the other class. The class from which another class is derived is known as the “parent” class or “base” class. The class which derives from another class is known as the “child” class or “derived” class. Inheritance in OOPs fosters code reusability. This feature of python helps really helps in developing various software applications, web applications, etc. 

We don’t need to write repetitive code for a new class if some existing class already has it. 

Example:

# base class
class Animal:
    
    def sound(self):
        print("I can make sounds!")
    
    def hunt(self):
        print("I can hunt")

# derived class
class Dog(Animal):
    
    def sound(self):
        print("I can bark as I am a dog")

# Create object of the Dog class
dog1 = Dog()

# Calling members of the base class
dog1.sound()
dog1.hunt()

# Calling member of the derived class
dog1.sound();

Output:

I can bark as I am a dog
I can hunt
I can bark as I am a dog

Encapsulation in Python

Encapsulation is the process in which data and functions are binded together in a single unit. In encapsulation, data is hidden from other functions and classes. Therefore, it is also known as “data hiding”. To prevent changes from an external entity, only object’s methods can change the object’s variables. In Python, class forms the basis of encapsulation.

Polymorphism in Python

The word poly means “many” and morphism means “forms”. Therefore, polymorphism combined means many forms. In Python, we can create a function or variable that has many forms. 

There are two types of polymorphism in Python-

  • Run-time polymorphism– It is performed during the run-time. It can be achieved through method overriding. 
  • Compile-time polymorphism– It is performed during the compiling time. It can be achieved by method overloading. 

Polymorphism also helps in code reusability and saves time. 

Is Python fully object-oriented? 

Python is not considered fully object-oriented as it does not have the “private” access specifier like Java. There are other features that support OOPs like encapsulation, abstraction, inheritance, polymorphism, objects and classes etc. In Python, everything is considered an object, and every object has a type. So primitive data types like integers and strings are objects in Python. 

Hence, we can say that Python may not be fully object-oriented but provides almost all the features of OOPs and hence can be considered an Object-oriented Programming language. This OOPs feature helps in real life applications also, like in software development, web applications, etc. If you are getting started with software development or full stack development etc., then learning python in prior will help you a lot. It is easy, fun to learn and plenty of resources available out there online. 

Conclusion

In conclusion, object-oriented programming (OOP) is a programming approach that emphasizes organizing a program based on its data, using objects and classes that resemble real-world entities. OOP aims to emphasize data and security, code reusability, modularity, and resemblance to the real world. In Python, OOP plays a crucial role in overcoming the limitations of procedural-oriented programming. The fundamental principles of OOP are encapsulation, inheritance, polymorphism, and abstraction. Python’s class is a blueprint for creating similar kinds of objects that have certain attributes and methods associated with them.

Related Articles:

Functions in Python with Examples

Loops in Python 3 with Examples

7 Python Operators with Examples

Python Introduction for Programmers [Part 1]

6 Python Conditional Statements with Examples

Inheritance in python with examples

Encapsulation and Polymorphism in Python with Examples

Python RegEx with Examples

Python Exception Handling with Examples

Python Datetime with Examples

Reference:

Python file handling official page

FOSS TechNix

FOSS TechNix (Free,Open Source Software's and Technology Nix*) founded in 2019 is a community platform where you can find How-to Guides, articles for DevOps Tools,Linux and Databases.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap