Python has Public, Protected, and Private access modifiers. Access modifiers are used to restrict access to the variables and methods of the class.
Examples of access modifiers in Python
Simple example code.
Public Access Modifier:
Example public member accessed from outside the class environment.
class Student: schoolName = 'Global School' # class attribute def __init__(self, name, age): self.name = name self.age = age # public member function def get_age(self): print("Age: ", self.age) std = Student("John", 21) print(std.schoolName) print(std.name) std.get_age()
Protected Access Modifier:
The members declared as Protected are accessible from outside the class but only in a class derived from it that is in the child or subclass.
Use the underscore ‘_’ symbol before the data member to make it a protected member of the class.
class Student: # protected data members _name = None _roll = None _age = None # constructor def __init__(self, name, roll, age): self._name = name self._roll = roll self._age = age # protected member function def _display(self): # accessing protected data members print("Roll: ", self._roll) print("Age: ", self._age) # derived class class Stu(Student): # constructor def __init__(self, name, roll, branch): Student.__init__(self, name, roll, branch) # public member function def displayDetails(self): # accessing protected data members of super class print("Name: ", self._name) # accessing protected member functions of super class self._display() # creating objects of the derived class obj = Stu("Jimmy", 123456, 21) # calling public member functions of the class obj.displayDetails()
Private Access Modifier:
These members are only accessible from within the class. It can’t Access outside. You can declare private members by adding a double underscore ‘__’ symbol before the data member of that class.
class Student: # protected data members __name = None __roll = None __age = None # constructor def __init__(self, name, roll, age): self.__name = name self.__roll = roll self.__age = age # protected member function def __display(self): # accessing protected data members print("Roll: ", self.__roll) print("Age: ", self.__age) # public member function def get_display(self): # Access private member function self.__display() # creating object obj = Student("Mike", 123456, 15) # calling public member function of the class obj.get_display()
Do comment if you have any doubts and suggestions on this Python basic tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.