Access Modifiers in Python
What Are Access Modifiers?
Access modifiers in Python control the visibility and accessibility of class members (variables and methods). Python provides three levels of access control:
Modifier | Syntax | Access Level |
---|---|---|
Public | name | Accessible from anywhere |
Protected | _name | Accessible within class and subclasses |
Private | __name | Accessible only within the class |
Unlike some other languages, Python does not enforce access modifiers strictly but uses naming conventions to indicate intent.
1. Public Access Modifier
- Members are accessible from anywhere.
Example:
class Person:
def __init__(self, name):
self.name = name # public variable
p = Person("Simran")
print(p.name)
Output:
Simran
2. Protected Access Modifier
- Prefix with a single underscore:
_name
- Accessible within the class and its subclasses.
- Treated as a convention only (not enforced).
Example:
class Person:
def __init__(self, name):
self._name = name # protected variable
class Student(Person):
def show(self):
print("Name:", self._name)
s = Student("Dharmendra")
s.show()
Output:
Name: Dharmendra
3. Private Access Modifier
- Prefix with double underscore:
__name
- Not accessible outside the class.
- Internally name-mangled as
_ClassName__variable
.
Example:
class Account:
def __init__(self, balance):
self.__balance = balance # private variable
def show_balance(self):
print("Balance:", self.__balance)
a = Account(1000)
a.show_balance()
Output:
Balance: 1000
Attempting to Access Private Variable
print(a.__balance)
Output:
AttributeError: 'Account' object has no attribute '__balance'
Accessing Private Variable (Not Recommended)
print(a._Account__balance)
Output:
1000
Summary Table
Modifier | Syntax | Scope | Enforced? |
---|---|---|---|
Public | name | Anywhere | No |
Protected | _name | Class + Subclass | No |
Private | __name | Only inside the class (mangled) | Partially |