Python Access Modifiers

Access modifiers are used in an object-oriented programming language to limit the access of the variable and functions of a class. Most of the object-oriented programming languages use three types of access modifiers these are public, protected, and private.


Public Access Modifier

Public members (generally methods declared in a class) are accessible from outside the class. The object of the same class is required to invoke a public method. This arrangement of private instance variables and public methods ensures the principle of data encapsulation.

Example of Public access Modifier

class employee:
    def __init__(self, name, sal):
        self.name=name
        self.salary=sal

e1=Employee("Kiran",10000)
print(e1.salary)  # salary is public attribute

# we can access employee class's attributes and also modify their values
e1.salary=20000
print(e1.salary)
Output of the above program is

10000
20000


Protected Access Modifier

Protected members of a class are accessible from within the class and are also available to its sub-classes. No other environment is permitted access to it. This enables the specific resources of the parent class to be inherited by the child class. By adding a prefix _(single underscore) to instance variables, we can make it protected.

Example of Protected Access Modifier

class employee:
    def __init__(self, name, sal):
        self._name=name    # name and sal are protected
        self._salary=sal

e1=Employee("Kiran",10000)
print(e1._salary)  # salary is protected attribute

e1._salary=20000
print(e1._salary)
Output of the above program is

10000
20000


Private Access Modifier

Private members of a class are denied access to the environment outside the class. We can handle them only within the class. By adding a prefix __(double underscore) to instance variables and functions of a class, we can make it private.

Example of Private Access Modifier

class employee:
    def __init__(self, name, sal):
        self.__name=name          # name and sal are private
        self.__salary=sal

e1=Employee("Kiran",10000)
print(e1.__salary)  # salary is the private attribute

e1.__salary=20000
print(e1.__salary)
Output of the above program is

Traceback (most recent call last):
File “E:/python/khusboo/test-py.py”, line 6, in
e1=Employee(“Kiran”,10000)
NameError: name ‘Employee’ is not defined

Note: Python doesn’t have any mechanism that effectively restricts access to any instance variable or method. Python prefix the name of the variable/method with a single or double underscore to match the behavior of protected and private access specifiers.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.