Open In App

Protected variable in Python

Last Updated : 10 Jan, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:




# program to illustrate protected
# data members in a class 
  
  
# Defining a class
class Geek: 
      
    # protected data members 
    _name = "R2J"
    _roll = 1706256
      
    # public member function 
    def displayNameAndRoll(self): 
  
        # accessing protected data members 
        print("Name: ", self._name) 
        print("Roll: ", self._roll) 
  
  
# creating objects of the class         
obj = Geek() 
  
# calling public member 
# functions of the class 
obj.displayNameAndRoll() 


Output:

Name:  R2J
Roll:  1706256

Example 2: During Inheritance




# program to illustrate protected
# data members in a class 
  
  
# super class 
class Shape: 
      
    # constructor 
    def __init__(self, length, breadth): 
        self._length = length
        self._breadth = breadth 
          
    # public member function 
    def displaySides(self): 
  
        # accessing protected data members 
        print("Length: ", self._length) 
        print("Breadth: ", self._breadth) 
  
  
# derived class 
class Rectangle(Shape): 
  
    # constructor 
    def __init__(self, length, breadth): 
  
        # Calling the constructor of
        # Super class
        Shape.__init__(self, length, breadth) 
          
    # public member function 
    def calculateArea(self): 
                      
        # accessing protected data members of super class 
        print("Area: ", self._length * self._breadth) 
                      
  
# creating objects of the 
# derived class         
obj = Rectangle(80, 50
  
# calling derived member 
# functions of the class
obj.displaySides()
  
# calling public member
# functions of the class 
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.


Level up your coding with DSA Python in 90 days! Master key algorithms, solve complex problems, and prepare for top tech interviews. Join the Three 90 Challenge—complete 90% of the course in 90 days and earn a 90% refund. Start your Python DSA journey today!


Next Article
Practice Tags :

Similar Reads

Create Password Protected Zip of a file using Python
ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep re
2 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be changed by the developer. The implementation of scopin
9 min read
Python | setting and retrieving values of Tkinter variable
Tkinter supports some variables which are used to manipulate the values of Tkinter widgets. These variables work like normal variables. set() and get() methods are used to set and retrieve the values of these variables. The values of these variables can be set using set() method or by using constructor of these variables.There are 4 tkinter variabl
3 min read
Python | Accessing variable value from code scope
Sometimes, we just need to access a variable other than the usual way of accessing by it's name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let's talk about some of these functions. Method #1 : Usi
3 min read
Python Program to swap two numbers without using third variable
The task of swapping two numbers without using a third variable in Python involves taking two input values and exchanging their values using various techniques without the help of a temporary variable. For example, if x = 5 and y = 7 then after swapping, x = 7 and y = 5.Using tuple unpackingTuple unpacking is the most preferred way to swap two vari
4 min read
__file__ (A Special variable) in Python
A double underscore variable in Python is usually referred to as a dunder. A dunder variable is a variable that Python has defined so that it can use it in a "Special way". This Special way depends on the variable that is being used. Note: For more information, refer to Dunder or magic methods in Python The __file__ variable: __file__ is a variab
2 min read
How to check if a Python variable exists?
Variables in Python can be defined locally or globally. There are two types of variables first one is a local variable that is defined inside the function and the second one are global variable that is defined outside the function. Method 1: Checking the existence of a local variableTo check the existence of variables locally we are going to use th
3 min read
PYTHONPATH Environment Variable in Python
Python's behavior is greatly influenced by its environment variables. One of those variables is PYTHONPATH. It is used to set the path for the user-defined modules so that it can be directly imported into a Python program. It is also responsible for handling the default search path for Python Modules. The PYTHONPATH variable holds a string with the
2 min read
Unused local variable in Python
A variable defined inside a function block or a looping block loses its scope outside that block is called ad local variable to that block. A local variable cannot be accessed outside the block it is defined. Example: Python3 # simple display function def func(num): # local variable a = num print("The number is :", str(a)) func(10) # gen
4 min read
Unused variable in for loop in Python
Prerequisite: Python For loops The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop. Example: Python3 # i,j - loop variable # loop-1 print("Using the loop variable inside :") # used loop variable for i in range(0, 5): x = (i+1)*2 print(x, end
3 min read
  翻译: