In simple English,
Access Modifiers help you control:
βWho can access which part of the class?β
π Public (default)
-
Anyone can access it from anywhere
-
No special symbol needed
class BankAccount:
def __init__(self, balance):
self.balance = balance # public
def show_balance(self):
print(f"Balance is {self.balance}")
acc = BankAccount(500)
acc.show_balance() # β
works
print(acc.balance) # β
also works
π Private β __ (double underscore)
-
Only accessible inside the class
-
Outside access gives error
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private
def show_balance(self):
print(f"Balance is {self.__balance}")
acc = BankAccount(500)
acc.show_balance() # β
works
print(acc.__balance) # β error
But yes, you can still access it with a trick (not recommended):
print(acc._BankAccount__balance) # β
works (name mangling)
π‘ Protected β _ (single underscore)
-
It means: βthis is not for public useβ
-
Still accessible, but considered internal
-
Useful for child classes
class BankAccount:
def __init__(self, balance):
self._balance = balance # protected
class SavingsAccount(BankAccount):
def show(self):
print(f"Balance: {self._balance}")
acc = SavingsAccount(1000)
acc.show() # β
works
print(acc._balance) # β
works but not best practice
π Example with all 3
class BankAccount:
def __init__(self, name, balance):
self.name = name # public
self._account_type = "Saving" # protected
self.__balance = balance # private
def get_balance(self): # public method
return self.__balance
def __update_balance(self, amount): # private method
self.__balance += amount
π Summary
Modifier | Symbol | Meaning |
|---|---|---|
Public | Accessible from everywhere | |
Protected |
| Access within class & child |
Private |
| Only inside the class |