When working with the Python programming language, one of the most important object-oriented concepts is access modifiers. These modifiers determine how variables and methods of a class can be accessed or modified.
Unlike languages like Java or C++, Python doesn’t enforce strict access rules. Instead, it relies on naming conventions and the discipline of developers. In this blog from Tpoint Tech, we’ll explain Access Modifiers in Python—Public, Protected, and Private—with simple code examples.
Why Do We Need Access Modifiers?
Access modifiers help in:
- Encapsulation: Grouping variables and methods to protect data.
- Security: Prevents accidental or unauthorized access.
- Code clarity: Makes clear which parts of code are safe to use and which are internal.
Now, let’s look at each type with code examples.
Public Access Modifier
By default, everything in Python is public unless specified otherwise. Public members can be accessed anywhere inside or outside the class.
class Student:
def __init__(self, name, age):
self.name = name # Public attribute
self.age = age # Public attribute
def show_details(self): # Public method
print(f"Name: {self.name}, Age: {self.age}")
# Creating an object
s1 = Student("Rahul", 21)
# Accessing public members
print(s1.name) # Output: Rahul
s1.show_details() # Output: Name: Rahul, Age: 21
Key Point: Public members are open and accessible everywhere.
Protected Access Modifier
In Python, protected members are indicated by a single underscore (_
) prefix. These are not strictly protected but are meant to be accessed only within the class and its subclasses.
class Employee:
def __init__(self, name, salary):
self._salary = salary # Protected attribute
self.name = name
def _show_salary(self): # Protected method
print(f"Salary: {self._salary}")
class Manager(Employee):
def show_info(self):
# Subclass can access protected members
print(f"Manager: {self.name}, Salary: {self._salary}")
e1 = Manager("Amit", 50000)
e1.show_info() # Allowed (inside subclass)
print(e1._salary) # Allowed, but discouraged
Key Point: Protected members can be accessed outside but should be treated as internal.
Private Access Modifier
Private members in Python are declared using double underscores (__
). Python uses name mangling to make it harder to access them from outside the class.
class BankAccount:
def __init__(self, account_holder, balance, pin):
self.account_holder = account_holder
self.__balance = balance # Private attribute
self.__pin = pin # Private attribute
def deposit(self, amount):
self.__balance += amount
print(f"Deposited {amount}. New Balance: {self.__balance}")
def __show_pin(self): # Private method
print(f"PIN: {self.__pin}")
# Creating an object
acc = BankAccount("Ravi", 1000, 1234)
# Accessing public method
acc.deposit(500) # Output: Deposited 500. New Balance: 1500
# Direct access to private members (will fail)
# print(acc.__balance) # AttributeError
# Access using name mangling (not recommended)
print(acc._BankAccount__balance) # Output: 1500
Key Point: Private members provide the highest level of protection in Python.
Comparison of Access Modifiers in Python
Modifier | Syntax | Accessibility | Example |
---|---|---|---|
Public | var |
Everywhere | student.name |
Protected | _var |
Within class and subclasses (convention) | employee._salary |
Private | __var |
Only within class (via name mangling) | account.__balance |
Real-World Example
Let’s say you’re building a Banking System in the Python programming language.
class Account:
def __init__(self, name, balance, pin):
self.name = name # Public
self._balance = balance # Protected
self.__pin = pin # Private
def get_balance(self, pin):
if pin == self.__pin:
return f"Balance: {self._balance}"
else:
return "Invalid PIN!"
acc = Account("Karan", 5000, 4321)
print(acc.name) # Public → Karan
print(acc._balance) # Protected → 5000 (not recommended)
print(acc.get_balance(4321)) # Private via method → Balance: 5000
This structure ensures sensitive information (PIN) is private, balance is semi-restricted, and name is public.
Best Practices
1. Use underscores consistently – Respect Python’s naming conventions.
2. Encapsulation matters – Always keep sensitive data private.
3. Don’t over-restrict – Not every variable needs to be private.
4. Readable code – Make your intentions clear for other developers.
Conclusion
Understanding Access Modifiers in Python—Public, Protected, and Private—is key for writing clean, secure, and professional code in the Python programming language. While Python doesn’t enforce access restrictions strictly, its conventions promote discipline and good practices.
At Tpoint Tech, we recommend developers follow these conventions to ensure better readability, maintainability, and security in their projects. By applying access modifiers wisely, you can structure your classes effectively and safeguard sensitive data.
So remember:
- Use public for open access.
- Use protected for controlled sharing.
- Use private for critical data security.
This simple approach will elevate your Python coding skills and make your applications more robust.
Top comments (0)