Welcome to the “Encapsulation” tutorial!
Overview
Encapsulation hides internal state and protects data integrity. Python uses naming conventions:
- Public:
attribute
- Protected:
_attribute
- Private:
__attribute
Example
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
acct = BankAccount(100)
acct.deposit(50)
print(acct.get_balance()) # 150
# print(acct.__balance) # AttributeError
Key Takeaways
- Use
_
or__
prefixes to signal protected/private. - Provide methods to interact with hidden data.
Happy coding!
Comments
Post a Comment