Junior — Middle
Could you give an example of how encapsulation principle is applied in your code in practice?
sobes.tech AI
Answer from AI
The principle of encapsulation in Python is often implemented by hiding internal data and providing access to it through class methods. For example, attributes can be made private (using double underscores) and access can be managed through getters and setters.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance()) # 1300
Thus, the internal state of the object is protected from direct external modification, ensuring data control and security.