Protected variable in Python
Last Updated :
10 Jan, 2020
Prerequisites: Underscore ( _ ) in Python
A 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:
class Geek:
_name = "R2J"
_roll = 1706256
def displayNameAndRoll( self ):
print ( "Name: " , self ._name)
print ( "Roll: " , self ._roll)
obj = Geek()
obj.displayNameAndRoll()
|
Output:
Name: R2J
Roll: 1706256
Example 2: During Inheritance
class Shape:
def __init__( self , length, breadth):
self ._length = length
self ._breadth = breadth
def displaySides( self ):
print ( "Length: " , self ._length)
print ( "Breadth: " , self ._breadth)
class Rectangle(Shape):
def __init__( self , length, breadth):
Shape.__init__( self , length, breadth)
def calculateArea( self ):
print ( "Area: " , self ._length * self ._breadth)
obj = Rectangle( 80 , 50 )
obj.displaySides()
obj.calculateArea()
|
Output:
Length: 80
Breadth: 50
Area: 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.