OOPS Concepts in Python with Real-Time Examples
Python has been ranked as one of the most popular programming languages in recent years. As a result, the demand for Python developers is multiplying. According to a recent study, more than 9,000 remote Python jobs are currently available. This means that the need for skilled Python developers, who know the language well, is growing rapidly. If you wish to pursue a career as a Python developer you must understand the fundamentals of OOPs concepts in Python with real-time examples.
The term ‘Object Oriented Programming’ (OOP) in relation to Python has attracted much attention over the years in the tech industry. In this blog, we will give you a detailed overview of OOPs in Python and simplify this concept for your better understanding.
What is Object Oriented Programming in Python?
Object-Oriented Programming (OOP) is a robust model that enables users to link every feature of a program with real-world objects or concepts. It helps to write more organized and reusable codes. For example, we can create a modular code using classes and objects which can be easily tested and debugged. Python is an OOPs language making it ideal for developing various applications.
OOP comprises five essential concepts, they are encapsulation, inheritance, polymorphism, abstraction, and classes and objects. They are discussed below in detail:
Classes and Objects
A class is also known as a blueprint. It is used for developing objects. The following are the properties of classes:
- Classes are created using the ‘class’ keyword in Python.
- The main aim of classes is to define a set of properties and methods that an object of that class will have.
The instance of a class is referred to as an object. This instance has its own set of properties. It is also capable of performing actions using methods.
Benefits of Classes
Classes offer several benefits. Some of them are:
- It allows the encapsulation of data and functions within a single entity. This leads to better readability of the code.
- Classes allow code reusability. As we can create multiple objects from the same class.
- They help improve security by limiting access to sensitive data.
Here is an example of a class in Python:
class Rect: def __init__(self, wd, ht): self.wd = width self.ht = height def A(self): return self.wd * self.ht def P(self): return 2 * (self.wd + self.ht) |
Encapsulation
Encapsulation is the technique of binding data and methods within a single class. It is implemented using access modifiers. Python classes have the following modifiers:
- Public
- Private
- Protected
These access modifiers determine the accessibility of a class’s properties and methods. They prevent unwanted modification outside of the class.
Benefits Of Encapsulation
Some of the benefits offered by Encapsulation include:
- Encapsulation prevents unauthorized access to the data.
- It increases the modularity and reusability of code.
- It hides the implementation details of the object making it very secure.
Here is an example of encapsulation in Python:
class Student: def __init__(self, name, age, email): self.__name = name # private attribute self.__age = age # private attribute self.__email = email # private attribute def get_name(self): return self.__name def set_name(self, new_name): self.__name = new_name def get_age(self): return self.__age def set_age(self, new_age): if new_age < 0: print(“Age cannot be negative.”) else: self.__age = new_age def get_email(self): return self.__email def set_email(self, new_email): self.__email = new_email |
Inheritance
Deriving a new class from an existing one is known as inheritance. Inheritance has the following properties:
- The original class is called the parent or base class.
- The new class derived from it is termed the child or derived class.
- It has the ability to inherit all the properties of the parent class.
Benefits of Inheritance
Inheritance offers several benefits, such as:
- It allows us to reuse code and build on existing classes. It promotes reusability which leads to more robust and less error-prone programs.
- Allows for easy maintenance of code by creating a hierarchy of classes.
You can pursue a Python course if you want to understand inheritance and other Python OOPs concepts easily.
Example of Inheritance in Python:
class Person(object): # Constructor def __init__(self, name): self.name = name # To get name def getName(self): return self.name # To check if this person is an employee def isEmployee(self): return False # Inherited or Subclass (Note Person in bracket) class Employee(Person): # Here we return true def isEmployee(self): return True # Driver code emp = Person(“Demo1”) # An Object of Person print(emp.getName(), emp.isEmployee()) emp = Employee(“Demo2”) # An Object of Employee print(emp.getName(), emp.isEmployee()) |
Polymorphism
Polymorphism allows us to perform a single action in different ways. It allows us to have more than one method with the same name, as long as they have different parameters. Some features of polymorphism are:
- It allows objects of different classes to be used interchangeably.
- It helps to reduce the complexity of code by providing a way to abstract away differences between related classes.
- It enables method overloading and method overriding. Method overloading allows multiple methods with the same name but different parameters to coexist within a single class.
- It leads to loosely coupled programs that can handle new types without recompilation.
Benefits of Polymorphism
It provides the following benefits:
- Polymorphism increases the flexibility of code. It allows objects of different classes to be treated as a part of the same class.
- It helps in code reusability. Since multiple classes share the same ion names.
- It allows the same method or function name to be used for different classes.
Example of Polymorphism in Python
class A: def __init__(self, name): self.name = name def talk(self): pass class Dog(A): def talk(self): print(‘Wooof!’) class Cat(A): def talk(self): print(‘Meoww!’) def make_A_talk(A): A.talk() my_dog = Dog(‘Rufus’) make_A_talk(my_dog) my_cat = Cat(‘Fluffy’) make_A_talk(my_cat) |
Abstraction
Abstraction allows us to focus on what the object does instead of how it does it. Some of the features of abstraction are:
- It only showcases the necessary information to the user.
- The classes with one or more abstract methods are known as Abstract classes.
- Whereas an abstract method is declared but does not hold an implementation.
Benefits of Abstraction
Abstraction provides several benefits, such as:
- It helps in minimizing the complexity of the code written.
- It makes the code reusable.
- It enhances security because it hides sensitive information from the user.
Example of Abstraction in Python
from abc import ABC, abstractmethod class Polygon(ABC): @abstractmethod def noofsides(self): pass class Triangle(Polygon): # overriding abstract method def noofsides(self): print(“I have 3 sides”) class Pentagon(Polygon): # overriding abstract method def noofsides(self): print(“I have 5 sides”) class Hexagon(Polygon): # overriding abstract method def noofsides(self): print(“I have 6 sides”) class Quadrilateral(Polygon): # overriding abstract method def noofsides(self): print(“I have 4 sides”) # Driver code R = Triangle() R.noofsides() K = Quadrilateral() K.noofsides() R = Pentagon() R.noofsides() K = Hexagon() K.noofsides() |
OOPs in Python Vs POP in Python
The major differences between Object Oriented Programming in Python and Procedural Oriented Programming are listed below:
Object Oriented Programming | Procedural Oriented Programming | |
Programming Method | Object Oriented Programming is a type of programming that is entirely based on objects | Procedural Oriented Programming is a linear type method of programming |
Focus | It focuses on objects and their behavior. | It concentrates on procedures or functions |
Data and Functions | It emphasizes on data over functions | It emphasizes on functions over data |
Code Organization | It enables the better readability of code | It can lead to a more complex code |
Code Reusability | It encourages code reusability and modularity | It has limited code reusability and modularity |
Approach to Problems | It represents real-world entities as objects | It represents real-world tasks as functions |
Code Maintenance | It enables easy maintenance of code by creating a hierarchy of classes | It can result in code that becomes difficult to maintain as it grows in size |
Key Features | It encourages encapsulation, abstraction, and inheritance | It does not have features like encapsulation, abstraction, and inheritance |
Real-World Examples of OOPs in Python
Some of the real-time examples of OOPs are:
Classes and Objects
An example of classes and objects can be a bookstore inventory. To manage your bookstore inventory efficiently, use a class called ‘Book’ with attributes like title, author, publisher, genre, and price. Create objects of this class for each book in your inventory with their specific attributes. This will help you organize and manage your inventory effectively. Each object represents a single book, making it easy to search for specific titles or authors and update the inventory as needed.
Encapsulation
Banking System is the perfect example of encapsulation. Banks use encapsulation to protect sensitive customer data. It wraps the private methods or variables. They can only be accessed through public methods with proper authentication.
Inheritance
Inheritance allows a child class to inherit the features and characteristics of its parent class. For example, an e-commerce website can create a Parent Product class and then derive multiple Child Product classes from it, like books, electronics, and clothes. This can help to reuse the common traits and manners of the Parent Product class.
Polymorphism
A music app can use polymorphism to play different audio. It will use a class named Player with a method named play(). It will accept different arguments depending on the format type. The application will be able to handle various formats seamlessly. You won’t have to create new methods or classes for each format.
Abstraction
Let’s take an example of an online food ordering system. It can use abstraction to hide the complex performance details of a Payment Gateway class from the users. It only needs to showcase the methods and properties necessary for making the payments.
Conclusion
We learned what is oops concept in Python and how it is crucial for building robust and scalable applications. These concepts, when used effectively, can help you write efficient and modular code in Python. Now that we have discussed these concepts in detail, start practicing and exploring them and take your programming skills to the next level.