Access specifiers or Access modifiers in Python Programming

Access ModifiersAccess specifiers or access modifiers in python programming are used to limit the access of class variables and class methods outside of class while implementing the concepts of inheritance. This can be achieved by: Public, Private and Protected keyword.

We can easily inherit the properties or behaviour of any class using the concept of inheritance. But some classes also holds the data (class variables and class methods) that we don’t want other classes to inherit. So, to prevent that data we used access specifiers in python.

NoteAccess modifiers in python are very helpful when we are using the concepts of inheritance. We can also apply the concept of access modifiers to class methods.

access specifiers in python - public, private and protected keyword

Believe me, we are going to keep it very simple: We are done with the definition of access modifiers in python. Next, we will see the syntax and then types of access specifiers (public, private and protected) in Python. Later a detailed example of each type of access specifiers.

Syntax example :

#defining class Student
class Student:
    #constructor is defined
    def __init__(self, name, age, salary):
        self.age = age             # public Attribute
        self._name = name          # protected Attribute 
        self.__salary = salary     # private Attribute

    def _funName(self):            # protected method
        pass
 
    def __funName(self):           # private method
        pass

# object creation 
obj = Student("pythonlobby",21,45000)

Detailed Explanation

  • I’m assuming that you are already familiar with the concept of classes, constructor and methods.
  • In the above syntax example, inside the class constructor method (__init__) there are three class variables i.e. age, name and salary.
  • If we notice carefully, class variable age, name and salary is given followed by a self keyword.
  • But also name and salary are defined followed by a single underscore (‘_’) and double underscore (‘__’) respectively.
  • So, the point here is if any class variable is declared without followed by any underscore it means that variable is public by default.
  • If any class variable is declared followed by a single underscore it means that the variable is a protected variable.
  • If any class variable is declared followed by a double underscore it means that the variable is a private variable.
  • The same naming convention implies for methods also.
  • This example is just for understanding how we declare a public, protected and private property of variable using access specifiers in python.

 

access specifiers in python programming

There are three types of access specifiers or access modifiers

  • 1). Public access modifier
  • 2). Private access modifier
  • 3). Protected access modifier

Public Access Modifier in Python

All the variables and methods (member functions) in python are by default public. Any instance variable in a class followed by the ‘self’ keyword ie. self.var_name are public accessed.

syntax:

# Syntax_public_access_modifiers

# defining class Student
class Student:
    # constructor is defined
    def __init__(self, age, name):
        self.age = age             # public Attribute
        self.name = name           # public Attribute

# object creation 
obj = Student(21,"pythonlobby")
print(obj.age)
print(obj.name)
21
pythonlobby

 

access specifiers in python

Let’s see some examples of access specifiers to understand the concepts better.

Example 1: Example of elaborating the use of Public Access Modifiers.

#Example_of_public_access_modifiers

class Student: 
	def __init__(self,age): 
	self.age = age 

class Subject(Student): 
	pass 

obj = Student(21)
obj1 = Subject() 
print(obj1.age) 
21

Detailed Explanation:

  • In the class Student, there is a variable age with public access.
  • Next, we have defined the empty class Subject and is inheriting the properties of class Student.
  • We have created the obj object for the Student class and the obj1 object for the Subject class.
  • Note carefully: We printed the age by using the object reference of the Subject class.
  • The Subject class is inheriting the property of the Student class.
  • As the class variable age of the class, Student is public access. Hence Subject class successfully inherited.
  • Hence the output is displayed.

Private Access Modifier

Private members of a class (variables or methods) are those members which are only accessible inside the class. We cannot use private members outside of class.

It is also not possible to inherit the private members of any class (parent class) to derived class (child class). Any instance variable in a class followed by self keyword and the variable name starting with double underscore ie. self.__varName are the private accessed member of a class.

Syntax:

# Private_access_modifiers 
class Student: 
    def __init__(self, age, name): 
        self.__age = age
        
        def __funName(self):
            self.y = 34
            print(self.y)

class Subject(Student):
    pass

obj = Student(21,"pythonlobby")
obj1 = Subject

# calling by object reference of class Student
print(obj.__age)
print(obj.__funName())

# calling by object reference of class Subject
print(obj1.__age)
print(obj1.__funName())
AttributeError: 'student' object has no attribute '__age'
AttributeError: 'student' object has no method '__funName()'
AttributeError: 'subject' object has no attribute '__age'
AttributeError: 'student' object has no method '__funName()'
  • NotePrivate members of a class cannot be accessed or inherited outside of class. If we try to access or to inherit the properties of private members to child class (derived class). Then it will show the error. See one more example given below for the proper understanding of the concept.

 

Example 2

# Example_of_using_private_access_modifiers
class Student:
    def __init__(self):
        self.name = "Adams Boi"  # Public
        self.__age = 39          # Private

class Subject(Student):
    pass

# object creation
obj = Student()
obj1 = Subject()

# calling using object ref. of Student class
print(obj.name)  # No Error
print(obj1.name) # No Error

# calling using object ref. of Subject class
print(obj.__age)  # Error
print(obj1.__age)  # Error
Adams Boi
Adams Boi
Error : pythonlobby AttributeError: 'Student' object has no attribute 'age'
Error : pythonlobby AttributeError: 'Subject' object has no attribute 'age'

Detailed Explanation:

  • In the class Student, there are two variables name with public access & age with private access.
  • Next, we have defined the empty class Subject and is inheriting the properties of class Student.
  • We have created the obj object for the Student class and the obj1 object for the Subject class.
  • Note carefully: We printed the “name” by using the object reference of Student and Subject class and it is accessed and inherited successfully.
  • But it encountered an error when accessing or trying to inherit the private property of class Student.
  • Private property of class cannot be accessed outside of the class and not even inherit.
  • Hence the output is displayed.

Protected Access Modifier  

Protected variables or we can say protected members of a class are restricted to be used only by the member functions and class members of the same class. And also it can be accessed or inherited by its derived class ( child class ). We can modify the values of protected variables of a class. The syntax we follow to make any variable protected is to write variable name followed by a single underscore (_) ie. _varName. 

  • NoteWe can access protected members of class outside of class even we can modify its value also. Now the doubt that arises is, public access modifiers follow the same except its syntax. Actually, protected access modifiers are designed so that responsible programmer would identify by their name convention and do the required operation only on that protected class members or class methods.

Syntax and Example 3:

#Syntax_protected_access_modifiers
class Student:
    def __init__(self):
        self._name = "PythonLobby.com"

    def _funName(self):
        return "Method Here"

class Subject(Student):
    pass

obj = Student()
obj1 = Subject()

# calling by obj. ref. of Student class
print(obj._name)      # PythonLobby.com
print(obj._funName())     # Method Here
# calling by obj. ref. of Subject class
print(obj1._name)     # PythonLobby.com
print(obj1._funName())    # Method Here
PythonLobby.com
Method Here

PythonLobby.com
Method Here

Detailed Explanation:

  • Public access modifiers follow the same except its syntax. Public access specifiers can be accessed by every class but properties of protected properties can only be accessed by its own class using object reference and it can be inherited to other class also.
  • Protected access specifiers are designed so that responsible programmer would identify by their name convention and do the required operation only on that protected class members or class methods.