Skip to content

Access Modifiers in Python

Access Modifiers in Python: Public, Private, and Protected

Access modifiers in Python define the visibility and accessibility of class members (attributes and methods). While Python doesn’t have explicit keywords like public, private, or protected as seen in some other languages, it achieves access control through naming conventions and the use of underscores. Let’s explore how access modifiers work in Python.

Public Access Modifier

In Python, all class members are public by default. We can access them from anywhere within the program. Let’s see an example of a public access modifier in Python.

public.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)
public.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1.roll)

Output:

command
C:\Users\username>python public.py
Name: John
Roll: 1
command
C:\Users\username>python public.py
Name: John
Roll: 1

In the above example, we have created two instance variables named namename and rollroll. We have initialized the namename and rollroll variables to the namename and rollroll parameters of the __init__()__init__() method. We have printed the namename and rollroll variables using the student1student1 object. The output shows that the namename and rollroll variables are unique to the object.

Private Access Modifier

In Python, we can use double underscores (____) to make a class member private. We can’t access private members from outside the class. Let’s see an example of a private access modifier in Python.

private.py
class Student:
    def __init__(self, name, roll):
        self.__name = name
        self.__roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.__name)
print('Roll:', student1.__roll)
private.py
class Student:
    def __init__(self, name, roll):
        self.__name = name
        self.__roll = roll
 
student1 = Student('John', 1)
print('Name:', student1.__name)
print('Roll:', student1.__roll)

Output:

command
C:\Users\username>python private.py
Traceback (most recent call last):
  File "private.py", line 6, in <module>
    print('Name:', student1.__name)
AttributeError: 'Student' object has no attribute '__name'
command
C:\Users\username>python private.py
Traceback (most recent call last):
  File "private.py", line 6, in <module>
    print('Name:', student1.__name)
AttributeError: 'Student' object has no attribute '__name'

In the above example, we have created two private instance variables named __name__name and __roll__roll. We have initialized the __name__name and __roll__roll variables to the namename and rollroll parameters of the __init__()__init__() method. We have tried to print the __name__name and __roll__roll variables using the student1student1 object. The output shows that we can’t access private members from outside the class.

Protected Access Modifier

In Python, we can use a single underscore (__) to make a class member protected. We can access protected members from outside the class but within the same module. Let’s see an example of a protected access modifier in Python.

protected.py
class Student:
    def __init__(self, name, roll):
        self._name = name
        self._roll = roll
 
student1 = Student('John', 1)
print('Name:', student1._name)
print('Roll:', student1._roll)
protected.py
class Student:
    def __init__(self, name, roll):
        self._name = name
        self._roll = roll
 
student1 = Student('John', 1)
print('Name:', student1._name)
print('Roll:', student1._roll)

Output:

command
C:\Users\username>python protected.py
Name: John
Roll: 1
command
C:\Users\username>python protected.py
Name: John
Roll: 1

In the above example, we have created two protected instance variables named _name_name and _roll_roll. We have initialized the _name_name and _roll_roll variables to the namename and rollroll parameters of the __init__()__init__() method. We have printed the _name_name and _roll_roll variables using the student1student1 object. The output shows that we can access protected members from outside the class but within the same module.

Difference Between Public, Private, and Protected Access Modifiers

The following table summarizes the difference between public, private, and protected access modifiers in Python.

Access ModifierDescriptionExample
PublicPublic members can be accessed from anywhere within the program.self.name = nameself.name = name
PrivatePrivate members can’t be accessed from outside the class.self.__name = nameself.__name = name
ProtectedProtected members can be accessed from outside the class but within the same module.self._name = nameself._name = name

Access Table

The following table summarizes the access of class members from different places.

Class MemberInside ClassOutside ClassSame ModuleDifferent Module
Public
Private
Protected

Example: Access Modifiers in Python

Let’s see an example of access modifiers in Python.

access_modifiers.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self._roll = roll
        self.__age = 20
 
    def display(self):
        print('Name:', self.name)
        print('Roll:', self._roll)
        print('Age:', self.__age)
 
student1 = Student('John', 1)
student1.display()
print('Name:', student1.name)
print('Roll:', student1._roll)
print('Age:', student1.__age)
access_modifiers.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self._roll = roll
        self.__age = 20
 
    def display(self):
        print('Name:', self.name)
        print('Roll:', self._roll)
        print('Age:', self.__age)
 
student1 = Student('John', 1)
student1.display()
print('Name:', student1.name)
print('Roll:', student1._roll)
print('Age:', student1.__age)

Output:

command
C:\Users\username>python access_modifiers.py
Name: John
Roll: 1
Age: 20
Name: John
Roll: 1
Traceback (most recent call last):
  File "access_modifiers.py", line 16, in <module>
    print('Age:', student1.__age)
AttributeError: 'Student' object has no attribute '__age'
command
C:\Users\username>python access_modifiers.py
Name: John
Roll: 1
Age: 20
Name: John
Roll: 1
Traceback (most recent call last):
  File "access_modifiers.py", line 16, in <module>
    print('Age:', student1.__age)
AttributeError: 'Student' object has no attribute '__age'

In the above example, we have created three instance variables named namename, _roll_roll, and __age__age. We have initialized the namename, _roll_roll, and __age__age variables to the namename, rollroll, and 2020 parameters of the __init__()__init__() method. We have printed the namename, _roll_roll, and __age__age variables using the student1student1 object. The output shows that we can access public and protected members from outside the class but within the same module. However, we can’t access private members from outside the class.

Name Mangling

In Python, private members are not accessible from outside the class. However, we can access private members from outside the class using the name mangling technique. Let’s see an example of name mangling in Python.

syntax.py
object._className__variableName
syntax.py
object._className__variableName

In the above syntax, we have used the name mangling technique to access the private variable named variableNamevariableName of the class named classNameclassName using the object named objectobject. Let’s see an example of name mangling in Python.

name_mangling.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self._roll = roll
        self.__age = 20
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1._roll)
print('Age:', student1._Student__age)
name_mangling.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self._roll = roll
        self.__age = 20
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1._roll)
print('Age:', student1._Student__age)

Output:

command
C:\Users\username>python name_mangling.py
Name: John
Roll: 1
Age: 20
command
C:\Users\username>python name_mangling.py
Name: John
Roll: 1
Age: 20

In the above example, we have created three instance variables named namename, _roll_roll, and __age__age. We have initialized the namename, _roll_roll, and __age__age variables to the namename, rollroll, and 2020 parameters of the __init__()__init__() method. We have printed the namename, _roll_roll, and __age__age variables using the student1student1 object. The output shows that we can access public and protected members from outside the class but within the same module. However, we can’t access private members from outside the class. We have used the name mangling technique to access the private variable named __age__age of the class named StudentStudent using the object named student1student1.

Python Property Object

In Python, we can use the property()property() function to create a property object. We can use the property object to set and get the value of a property. Let’s see an example of a property object in Python.

property_syntax.py
property(fget=None, fset=None, fdel=None, doc=None)
property_syntax.py
property(fget=None, fset=None, fdel=None, doc=None)

In the above syntax, we have used the property()property() function to create a property object. We can pass the getter, setter, deleter, and docstring functions as arguments to the property()property() function. Let’s see an example of a property object in Python.

property_object.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self._roll = roll
        self.__age = 20
 
    def get_age(self):
        return self.__age
 
    def set_age(self, age):
        self.__age = age
 
    age = property(get_age, set_age)
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1._roll)
print('Age:', student1.age)
student1.age = 21
print('Age:', student1.age)
property_object.py
class Student:
    def __init__(self, name, roll):
        self.name = name
        self._roll = roll
        self.__age = 20
 
    def get_age(self):
        return self.__age
 
    def set_age(self, age):
        self.__age = age
 
    age = property(get_age, set_age)
 
student1 = Student('John', 1)
print('Name:', student1.name)
print('Roll:', student1._roll)
print('Age:', student1.age)
student1.age = 21
print('Age:', student1.age)

Output:

command
C:\Users\username>python property_object.py
Name: John
Roll: 1
Age: 20
Age: 21
command
C:\Users\username>python property_object.py
Name: John
Roll: 1
Age: 20
Age: 21

In the above example, we have created three instance variables named namename, _roll_roll, and __age__age. We have initialized the namename, _roll_roll, and __age__age variables to the namename, rollroll, and 2020 parameters of the __init__()__init__() method. We have created two methods named get_age()get_age() and set_age()set_age() to get and set the value of the __age__age variable. We have created a property object named ageage using the property()property() function. We have passed the get_age()get_age() and set_age()set_age() methods as arguments to the property()property() function. We have printed the namename, _roll_roll, and ageage variables using the student1student1 object. We have set the value of the ageage variable using the student1student1 object. The output shows that we can use the property object to set and get the value of a property.

Conclusion

In this tutorial, we have learned about access modifiers in Python like public, private, and protected. We have also learned how to use them in Python. We have also learned about the difference between public, private, and protected access modifiers in Python. We have also learned about the access table in Python. Finally, we have learned about the Python property object. Now you can use access modifiers in Python to control the visibility and accessibility of class members. You can also use the Python property object to set and get the value of a property. In the next tutorial, we will learn about inheritance in Python. We will also learn about different types of inheritance in Python. For more information on access modifiers in Python, you can refer to the official documentation. FOr more tutorials on Python, visit Python Central Hub.

Was this page helpful?

Let us know how we did