Object-Oriented Programming (OOP) Concepts in Python with Code Examples for your project
Table of contents
Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of "objects," which are essentially instances of a class that encapsulate data and behaviour. Python, being an object-oriented programming language, has robust support for OOP concepts. In this blog, we will explore the core OOP concepts in Python with code examples.
Classes and Objects
In Python, a class is defined using the class
keyword, followed by the name of the class. The class definition may contain data attributes and methods. Here's an example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_details(self):
return f"{self.name} is {self.age} years old."
In the above example, we define a class Person
that has two data attributes name
and age
and a method get_details
that returns a string containing the name and age of the person.
An object of a class is created by calling the class as if it were a function, passing any necessary arguments to the constructor. Here's an example:
person1 = Person("John", 30)
person2 = Person("Jane", 25)
In the above example, we create two objects of the class Person
and assign them to variables person1
and person2
.
Inheritance
Inheritance is the process by which a new class is created from an existing class. The new class, called the derived class or subclass, inherits all the data attributes and methods of the existing class, called the base class or superclass. Here's an example:
class Employee(Person):
def __init__(self, name, age, salary):
super().__init__(name, age)
self.salary = salary
def get_details(self):
return f"{super().get_details()} Salary: {self.salary}"
In the above example, we define a new class Employee
that inherits from the Person
class. The Employee
class has an additional data attribute salary
and overrides the get_details
method to include the salary.
Polymorphism
Polymorphism is the ability of objects to take on multiple forms. In Python, polymorphism is achieved through method overriding and method overloading.
Method overriding is when a derived class provides a different implementation of a method that is already defined in the base class. We saw an example of method overriding earlier when we defined the get_details
method in the Employee
class.
Method overloading is when a class has multiple methods with the same name but different parameters. Unfortunately, Python does not support method overloading in the traditional sense, but we can achieve similar functionality using default argument values. Here's an example:
class Calculator:
def add(self, x, y, z=0):
return x + y + z
c = Calculator()
print(c.add(2, 3)) # prints 5
print(c.add(2, 3, 4)) # prints 9
In the above example, we define a class Calculator
that has an add
method with two required parameters x
and y
and an optional parameter z
with a default value of 0. The add
method can be called with either two or three arguments.
Encapsulation
Encapsulation is the practice of hiding the implementation details of an object from the outside world. In Python, we can achieve encapsulation by making data attributes and methods private using the double underscore (__
) prefix. Here's an example:
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount > self.__balance:
raise ValueError("Insufficient balance")
self.__balance -= amount
def get_balance(self):
return self.__balance
In the above example, we define a class BankAccount
that has two private data attributes __account_number
and __balance
and three methods deposit
, withdraw
, and get_balance
. The deposit
and withdraw
methods modify the __balance
attribute, and the get_balance
method returns the current balance.
Note that the __account_number
and __balance
attributes are not accessible from outside the class. Attempting to access them will result in an AttributeError
.
Conclusion
In conclusion, object-oriented programming is a powerful programming paradigm that is widely used in Python and other programming languages. By using OOP concepts such as classes, objects, inheritance, polymorphism, and encapsulation, developers can write clean, modular, and reusable code. Python's support for OOP makes it an ideal language for developing large-scale applications and libraries. Understanding these core concepts and their implementation in Python is essential for any programmer looking to become proficient in OOP and develop high-quality data professional. Hope you got value out of this article. Subscribe to the newsletter to get more such blogs.
Thanks :)