How to Bundle Attributes and Methods with Encapsulation
Encapsulation
refers to the bundling of an object's data (attributes) and the methods that operate on that data into a single unit.
This allows us to hide the object's internal implementation and protect the data from improper external access.
In Python, you can implement encapsulation by prefixing attribute names with __
to make them private attributes
.
class ClassName:
# Constructor
def __init__(self):
# Private attribute
self.__private_attr = 0
In the code above, __private_attr
is a private attribute that cannot be accessed directly from outside the class.
It is customary to use two underscores (_
) to define private attributes in Python.
Role of Encapsulation
Encapsulation plays the following roles in object-oriented programming:
-
Providing an Interface
: An interface is a point of interaction for different systems or objects. Through encapsulation, you can interact with objects using provided methods without needing to know how the object works internally. -
Data Protection
: It safeguards important data of the object from unauthorized access.
Example of Using Encapsulation
The following code example defines an Account
class representing a bank account and safely manages the account balance through encapsulation.
class Account:
def __init__(self, balance):
# Private attribute
self.__balance = balance
# Deposit method
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return "Invalid deposit amount."
# Balance inquiry method
def get_balance(self):
return f"Current balance: ${self.__balance}"
# Create account with initial balance of $10000
account = Account(10000)
# Deposit $5000
account.deposit(5000)
# Check balance
print(account.get_balance())
In this example, __balance
is set as a private variable, making it inaccessible directly from outside the class.
Instead, you can safely manipulate or verify this variable through the deposit
and get_balance
methods.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.