What is Encapsulation in Python

Encapsulation in Python refers to the binding of data and functions into a single unit. It is the mechanism that restricts access to some of an object’s components.

Private variables are created in Python in order to implement encapsulation. A variable is considered private if its name starts with an underscore (_).

For example, let’s create a simple BankAccount class:

Python

1 class BankAccount:
2 def __init__(self, account_number, account_name):
3 self.account_number = account_number
4 self.account_name = account_name
5 self._balance = 0.0 # private variable
6
7 def deposit(self, amount):
8 self._balance += amount
9 return self._balance
10
11 def withdraw(self, amount):
12 if amount > self._balance:
13 raise ValueError("Insufficient balance")
14 self._balance -= amount
15 return self._balance
16
17 def get_balance(self):
18 return self._balance

In this class, we have created a private variable _balance. The deposit and withdrawal methods are used to manipulate this private variable.

However, please note that in Python, unlike some other programming languages like Java, there is no strict enforcement of access to private variables.

They are only intended to be “private by convention,” and other objects may access them if necessary. This is in contrast to some other programming languages, like Java or C++, where the compiler strictly enforces access to private variables.

Encapsulation offers the primary benefit of safeguarding an object’s internal state against unintentional external modification. This preserves the object’s integrity and upholds the data hiding principle.

About Author


Discover more from SURFCLOUD TECHNOLOGY

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from SURFCLOUD TECHNOLOGY

Subscribe now to keep reading and get access to the full archive.

Continue reading