Encapsulation
Encapsulation is the bundling of data (attributes) and methods that operate on the data into a single unit (class), and restricting access to some of the object’s components. This is achieved using private and protected attributes.
Example of Encapsulation
class BankAccount:
def __init__(self, account_holder, balance):
self.account_holder = account_holder
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if amount > 0 and amount <= self.__balance:
self.__balance -= amount
def get_balance(self):
return self.__balance
account = BankAccount("John Doe", 1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance()) # Output: 1300
# print(account.__balance) # AttributeError: 'BankAccount' object has no attribute '__balance'
Discover more from HintsToday
Subscribe to get the latest posts sent to your email.