Prerequisites:Underscore ( _ ) in PythonA Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a class.
Protected variables are those data members of a class that can be accessed within the class and the classes derived from that class. In Python, there is no existence of “Public” instance variables. However, we use
underscore '_' symbol to determine the access control of a data member in a class. Any member prefixed with an underscore should be treated as a non-public part of the API or any Python code, whether it is a function, a method or a data member.
Example 1:Python3# program to illustrate protected# data members in a class# Defining a classclassGeek:# protected data members_name="R2J"_roll=1706256# public member functiondefdisplayNameAndRoll(self):# accessing protected data membersprint("Name: ",self._name)print("Roll: ",self._roll)# creating objects of the classobj=Geek()# calling public member# functions of the classobj.displayNameAndRoll()
Output:Name: R2JRoll: 1706256
Example 2: During Inheritance
Python3# program to illustrate protected# data members in a class# super classclassShape:# constructordef__init__(self,length,breadth):self._length=lengthself._breadth=breadth# public member functiondefdisplaySides(self):# accessing protected data membersprint("Length: ",self._length)print("Breadth: ",self._breadth)# derived classclassRectangle(Shape):# constructordef__init__(self,length,breadth):# Calling the constructor of# Super classShape.__init__(self,length,breadth)# public member functiondefcalculateArea(self):# accessing protected data members of super classprint("Area: ",self._length*self._breadth)# creating objects of the# derived classobj=Rectangle(80,50)# calling derived member# functions of the classobj.displaySides()# calling public member# functions of the classobj.calculateArea()
Output:Length: 80Breadth: 50Area: 4000
In the above example, the protected variables
_length
and
_breadth
of the super class
Shape
are accessed within the class by a member function
displaySides()
and can be accessed from class
Rectangle
which is derived from the
Shape
class. The member function
calculateArea()
of class
Rectangle
accesses the protected data members
_length
and
_breadth
of the super class
Shape
to calculate the area of the rectangle.