In this tutorial, I will explain how to use access modifiers in Python to control the visibility and accessibility of class members (attributes and methods) from outside the class. Access modifiers play an important role in securing data from unauthorized access and preventing data exploitation.
As a Python developer at a tech startup in San Francisco, I recently faced an issue where another part of the codebase accidentally modified sensitive customer data stored in class variables. This made me realize the importance of properly using access modifiers to encapsulate and protect data within classes.
What are Access Modifiers in Python?
Access modifiers in Python are used to limit the access of class variables and methods outside of the class. They help enforce encapsulation, one of the fundamental principles of object-oriented programming (OOP). By specifying the visibility and accessibility of class members, you can control how they can be accessed and modified from outside the class.
Python provides three types of access modifiers:
- Public (default)
- Protected (prefixed with single underscore
_) - Private (prefixed with double underscore
__)
Let me explain each one in more detail with code examples.
Public Access Modifier in Python
In Python, all class members are public by default. They can be freely accessed and modified from anywhere inside or outside the class. Here’s an example:
class Customer:
def __init__(self, name, email):
self.name = name
self.email = email
john = Customer("John Doe", "john@example.com")
print(john.name) # Output: John Doe
john.email = "johndoe@example.com"
print(john.email) # Output: johndoe@example.comIn this example, the name and email attributes of the Customer class are public. They can be directly accessed and modified outside the class, as shown with the john object.
I executed the above Python code and added the screenshot below.

While public members offer flexibility, they also come with the risk of unintended modification and breaking encapsulation. It’s generally recommended to use public access judiciously and opt for protected or private access when needed.
Protected Access Modifier in Python
Protected members in Python are prefixed with a single underscore _. This is a convention to indicate that the member should be treated as protected and accessed only within the class and its subclasses. However, it’s important to note that this is merely a convention and doesn’t actually enforce strict access control.
Here’s an example of using protected access:
class BankAccount:
def __init__(self, account_number, balance):
self._account_number = account_number
self._balance = balance
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
else:
print("Insufficient funds!")
account = BankAccount("1234567890", 1000)
print(account._balance) # Output: 1000 (accessible but discouraged)
account.deposit(500)
account.withdraw(200)
print(account._balance) # Output: 1300I executed the above Python code and added the screenshot below.

In this example, the _account_number and _balance attributes are marked as protected using the single underscore prefix. The convention suggests that these attributes should be accessed only within the BankAccount class or its subclasses. However, as mentioned earlier, this is not strictly enforced, and the attributes can still be accessed from outside the class.
Private Access Modifier in Python
Private members in Python are prefixed with a double underscore __. They are intended to be strictly private and can only be accessed within the class itself. Python performs name mangling on private members, making them harder to access from outside the class.
Here’s an example demonstrating private access:
class User:
def __init__(self, username, password):
self.__username = username
self.__password = password
def login(self, username, password):
if self.__username == username and self.__password == password:
print("Login successful!")
else:
print("Invalid credentials!")
jenny = User("jenny123", "password123")
jenny.login("jenny123", "password123") # Output: Login successful!
print(jenny.__username) # Raises AttributeErrorI executed the above Python code and added the screenshot below.

Private access provides a strong encapsulation mechanism, preventing accidental or intentional modification of sensitive data from outside the class.
In this example, the __username and __password attributes are marked as private using the double underscore prefix. These attributes can only be accessed within the User class methods. Attempting to access them directly from outside the class will raise an AttributeError.
Best Practices for Using Python Access Modifiers
When deciding which access modifier to use for your class members, consider the following guidelines:
- Use public access for members that can be safely accessed and modified from outside the class.
- Use protected access for members that should be accessed only within the class and its subclasses.
- Use private access for sensitive data or internal implementation details that should not be accessed from outside the class.
It’s also a good practice to provide getter and setter methods (also known as accessor and mutator methods) for accessing and modifying protected and private members. This allows for controlled access and additional logic or validation if needed.
Example:
class Employee:
def __init__(self, name, salary):
self._name = name
self.__salary = salary
def get_salary(self):
return self.__salary
def set_salary(self, new_salary):
if new_salary > 0:
self.__salary = new_salary
else:
print("Invalid salary amount!")
sarah = Employee("Sarah Johnson", 5000)
print(sarah.get_salary()) # Output: 5000
sarah.set_salary(6000)
print(sarah.get_salary()) # Output: 6000In this example, the __salary attribute is private, and access to it is provided through the get_salary() and set_salary() methods. These methods allow for controlled access and ensure that the salary is set to a valid amount.
Conclusion
Access modifiers in Python provide a way to control the visibility and accessibility of class members. By using public, protected, and private access, you can enforce encapsulation, prevent unauthorized access, and maintain the integrity of your class data.
I hope this tutorial has clarified the concept of access modifiers in Python and provided practical examples to help you implement them effectively in your own projects. I hope this helps.
You may also like:
- Write a Variable to a File in Python
- Check if a Variable Contains an Integer in Python
- Check if a Variable is Not Empty in Python
- Check if a Float Variable is Empty in Python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.