How to Bundle Attributes and Methods with Encapsulation
Encapsulation
is the practice of combining 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, encapsulation is implemented by prefixing attribute names with double underscores (__
), making 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 indicate that an attribute is private in Python.
Role of Encapsulation
Encapsulation serves the following key purposes 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.
In object-oriented programming, encapsulation
refers to keeping the internal implementation details of an object exposed.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result