Access Modifiers in Python
The modifiers which define the scope and visibility of class members (variables and methods) in object-oriented programming are called access modifiers in Python. These modifiers are also known as access specifiers.
Python uses special notations, such as a single underscore (_) and double underscore (__) to control the visibility and accessibility of data attributes and methods of a class. However, other programming languages like Java uses the special keywords to control the visibility of class members.
Access modifiers play a pivotal role in securing the data from unauthorized access and in preventing it from being misused. They help in achieving encapsulation, data hiding, and code maintainability by controlling the visibility and accessibility of class members.
Most of the programming languages, including Python, supports mainly three primary access modifiers in a class. They are as:
- Public
- Protected
- Private
Let’s understand each modifier with the help of examples.
Public Access Modifier
The class members declared with public access modifier are easily accessible from any part of the program. We can access a public data attribute and method from anywhere in the code, both within and outside the class definition, without any restriction.
In Python, all the attributes and methods are public by default in a class. Therefore, we do not need any special notation to make a public member. Let’s take an example program based on the public access specifier.
Example 1:
# Python program to demonstrate public access modifier.
# Define a class.
class Student:
# Constructor method to initialize instance variables of the class.
def __init__(self, name, age):
self.name = name # public data member
self.age = age # public data member
# Public instance method
def display(self):
# Accessing public members from inside the method.
print("Name: ", self.name, "Age: ", self.age)
# Outside the class definition.
# Create an instance of class Student.
st = Student("Deepak", 30)
# Accessing public members from outside the class definition.
print("Name: ", st.name, "Age: ", st.age)
# Accessing public instance method from outside the class definition.
st.display()
Output:
Name: Deepak Age: 30
Name: Deepak Age: 30
In this example, we have accessed public instance variables from both inside class and outside the class. Similarly, we have accessed the public instance method display() from outside the class definition using a reference variable st. So, it is clear that public members of a class can be accessed from any place in the program.
Protected Access Modifier
The class members that are declared with the protected access modifier are only accessible from within the class and its subclasses. We can declare protected class members by adding a single underscore (_) before members of that class. In other words, we denote the protected variable and method by prefixing its name with a single underscore, like this:
_name
_rollno
_display()
Let’s take some example program based on the accessing of protected members of the class in Python.
Example 2:
# Define a base class.
class Student:
# Protected data members.
_name = None
_rollno = None
_elective = None
# Define a base class constructor to initialize data members.
def __init__(self, name, rollNo, elective):
self._name = name
self._rollNo = rollNo
self._elective = elective
# Define a protected method.
def _displayRollAndElective(self):
# Accessing protected data members inside the class definition.
print("Roll no: ", self._rollNo)
print("Elective: ", self._elective)
# Define a derived class that inherits from the base class.
class CSStudent(Student):
# Define a subclass constructor to initialize data members.
def __init__(self, name, rollNo, elective):
# Calling base class constructor using class name.
Student.__init__(self, name, rollNo, elective)
# Define a public method
def displayDetails(self):
# Accessing protected data members of base class.
print("Name: ", self._name)
# Accessing protected method of base class.
self._displayRollAndElective()
# Outside the class definition.
# Create an instance of derived class.
obj = CSStudent("Deepak", 12, "Data Science with Python")
# Calling public method of subclass.
obj.displayDetails()
Output:
Name: Deepak
Roll no: 12
Elective: Data Science with Python
In this example, we have defined a base class named Student that contains _name, _rollNo, and _elective protected data members as well as a protected method such as _displayRollAndElective().
Then, we have defined a class named CSStudent that is derived from the base class Student. The derived class CSStudent contains a public method named displayDetails that access the protected data members and protected method of the base class.
Example 3:
# Python program to demonstrate protected access modifier.
# Define a class.
class Student:
# Constructor method to initialize instance attributes of the class.
def __init__(self, name, age):
self._name = name # protected data member
self._age = age # protected data member
# Protected instance method
def _display(self):
# Accessing protected data members from inside the method.
print("Name: ", self._name, "Age: ", self._age)
# Outside the class definition.
# Create an instance of class Student.
st = Student("Tripti", 24)
# Accessing protected members from outside the class definition.
print("Name: ", st._name, "Age: ", st._age)
# Accessing protected instance method from outside the class definition.
st._display()
Output:
Name: Tripti Age: 24
Name: Tripti Age: 24
In this code, we have defined a class named Student with protected attributes _name and _age, as well as a protected method _display. We have created an instance of the Student class and then directly accessed the protected attributes _name and _age using dot notation (st._name and st._age) outside the class definition.
The above code is technically correct and will run without any error in Python. This is because Python doesn’t enforce strict access control mechanism like some other languages do.
Python allows us to use a single underscore prefix to indicate that a member is a protected and should not be accessed directly from outside the class. Therefore, you should follow and respect this convention voluntarily.
Private Access Modifiers
The class members declared with a private access modifier is only accessible within the class. Private access modifier is the most secure access modifier in Python that restricts access to the variable or method from outside the class entirely.
In Python, we can declare a private class member by adding a double underscore (__) before the member of that class. In other words, we can define a private member by prefixing its name with a double underscore, like this:
__name
__rollNo
__display()
Let’s take some example program based on the accessing of private members of the class.
Example 4:
class MyClass:
def __init__(self):
self.__private_var = 40 # private data member
# Private method
def __private_method(self):
print("This is a private method.")
# Creating an object of class MyClass.
obj = MyClass()
# Attempting to access private members will result in an AttributeError
print(obj.__private_var) # Raises an AttributeError
obj.__private_method() # Raises an AttributeError
Output:
AttributeError: 'MyClass' object has no attribute '__private_var'
Example 5:
class Teacher:
def __init__(self, name, salary):
self.__name = name # private member.
self.__salary = salary # private member
# Private method
def __display_salary(self):
print("Salary: ", self.__salary)
# Public method
def displayDetials(self):
# Accessing private members from the same class.
print("Name: ", self.__name)
self.__display_salary()
# Constructing an object of class Teacher.
teach = Teacher("Deepak", 60000)
# Accessing public method from outside the class.
teach.displayDetials()
# Accessing private method directly from outside the class will result AttributeError.
# teach.__display_salary()
Output:
Name: Deepak
Salary: 60000
In this example, we have tried to access private members of class from outside the class, but we got an AttributeError because we have declared them private in the class.
Benefits of Access Modifiers in Python
Access modifiers offer several advantages in Python. They are:
- Access modifiers enable encapsulation by hiding the internal implementation details of a class.
- They protect sensitive data from unauthorized access or modification.
- They make code more readable and maintainable by providing clear visibility and accessibility rules.
Encapsulation, Data Hiding and Access Modifiers
Encapsulation is a fundamental concept in object-oriented programming. It involves bundling data (attributes) and methods (functions) that operate on that data into a single unit, i.e., a class. Access modifiers play a crucial role in achieving encapsulation and data hiding by controlling the access to class members.
When it comes to inheritance in Python, access modifiers also play a vital role. Child classes can access public and protected members of their parent class, but private members remain inaccessible to them.
Summary of Access Modifiers
To summarize, access modifiers in Python help in controlling the visibility and accessibility of class members:
- Public Access Modifier: Accessible from anywhere.
- Protected Access Modifier: Accessible within the class and its subclasses.
- Private Access Modifier: Accessible only within the class.
In this tutorial, we have discussed access modifiers in Python with example programs. Hope that you will have understood how to control the visibility and accessibility of class members in Python. Stay tuned with the next tutorial where we will learn about the getter and setter methods in Python with the help of examples for the best practice.
Thanks for reading!!!





