Protected variable in Python

In programming, the concept of protected variables is used to create an access control system. In this system, we establish a hierarchy or level of access control. This concept solidifies the basis of object-oriented programming. The technical meaning of a protected variable remains the same but the syntax and behaviour may vary between different programming languages.

Python follows the conventional logic of accessing and manipulating the attributes and methods, but the representation and degree of enforcement of access control is a little different.

Understanding Protected Variables in Python

Protected variables in Python manage the internal use of the attributes and methods. These variables establish a convention that drives the logic of attribute access. In Python, we can declare a protected variable with the help of a single underscore (_) prefix.

This convention is used while declaring a method or a constructor within a class. We add the underscore as a prefix before a variable to make it protected.

Syntax

Following is the syntax to declare a protected variable ?

class MyClass:
    def __init__(self, value):
        self._protected_var = value  # Protected variable

Here, the __init__() method initializes the object's attributes and is called whenever an object is created. We use the self keyword to access and manipulate the attributes and methods.

We create a protected variable to tell other developers working on a codebase to treat this part of the code differently as its access is limited.

Significance of Protected Variables

The core idea behind the use of protected variables is to declare certain parts of the code as protected i.e., to prevent direct access of the variables from outside the environment. We can write the code in a meticulous manner and promote data encapsulation.

  • Protected variables help us to create different types of functioning units within the class interface. Each functioning unit can have its own rules of implementation.

  • Protected variables provide controlled methods (getters and setters) that can access the hidden or encapsulated information within the class. The code base becomes strong and readable as it allows the developers to treat different parts of code differently.

  • Protected variables also allow us to change the internal implementation details without affecting the external class/interface. Using protected variables, we can provide self-documenting code that explains the instructions to interact with the class and its data.

Example: Player Profile Management System

We will consider an example where we will code for a player profile management system. We will introduce protected variables to encapsulate the player information like: player name, rating, team name and salary. We will also use decorators (@property) to initialize the getter methods.

These methods will allow the coder to access the protected variables from outside and the decorators will prevent the internal data from being accidentally modified ?

class PlayerProfile:
    def __init__(self, player_name, team_name, rating):
        self._player_name = player_name
        self._team_name = team_name
        self._rating = rating
        self._salary = 0
        
    @property
    def player_name(self):
        return self._player_name
        
    @property
    def team_name(self):
        return self._team_name
        
    @property
    def rating(self):
        return self._rating
        
    @property
    def salary(self):
        return self._salary
        
    def calculate_salary(self):
        self._salary = self._rating * 200000

# Creating player object
player = PlayerProfile("Manoj Shukla", "Wolves", 8)

print(f"The player name is: {player.player_name}")
print(f"The team name is: {player.team_name}")
print(f"The player rating is: {player.rating}")

player.calculate_salary()
print(f"The player salary is: {player.salary} USD")
The player name is: Manoj Shukla
The team name is: Wolves
The player rating is: 8
The player salary is: 1600000 USD

Accessing Protected Variables

Unlike languages like Java or C++, Python allows access to protected variables from outside the class, though it's not recommended ?

class Example:
    def __init__(self):
        self._protected = "I'm protected"

obj = Example()

# This works but violates convention
print(obj._protected)

# Recommended approach using property
print(obj.protected if hasattr(obj, 'protected') else "Use getter methods")
I'm protected
Use getter methods

Comparison With Other Languages

The fundamental idea of controlling the access remains the same in all programming languages but the manner in which we implement the logic differs.

Language Declaration Enforcement
Python Single underscore (_) Convention-based
Java protected keyword Compiler enforced
C++ protected: section Compiler enforced

In most programming languages, protected variables can only be accessed within the class hierarchy, but Python allows access from outside the class. Although it is not encouraged as it goes against the convention.

Conclusion

Protected variables in Python use a single underscore prefix to indicate restricted access by convention. They promote data encapsulation and provide a way to signal to other developers which attributes should be treated as internal implementation details.

Updated on: 2026-03-27T16:23:23+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements