Guidelines

How to Use Private Variables in a Class

Private Variables are special variables that can only be accessed within the class itself.

These variables protect important data from being modified directly from outside, facilitating the implementation of encapsulation.

In Python, private variables are denoted by prefixing the variable name with two underscores (__).

Note: A single leading underscore denotes protected variables, which are designed to be accessed within a class and its subclasses. Unlike private variables, they can be accessed externally but it is not recommended.


Example of Using Private Variables
class MyClass: def __init__(self): # Private variable self.__private_var = 10 # Method to return the value of the private variable def get_private_var(self): return self.__private_var obj = MyClass() print(obj.get_private_var()) # Outputs 10 # print(obj.__private_var) # Raises AttributeError: direct access is not allowed

In the code above, __private_var is a private variable of the MyClass.

If you try to access __private_var directly from outside the class like obj.__private_var(), an AttributeError will be raised.

Thus, by restricting access to private variables to within the class methods, private variables effectively safeguard an object's information.


Characteristics of Private Variables

Private variables have the following characteristics:

  • Data Protection: Variables can only be accessed within the class, preventing unauthorized or incorrect modifications from outside.

  • Convenient Methods Provided: Safe handling of variables is ensured by using pre-defined methods of the class.

Example of Using Private Variables
class Account: def __init__(self, balance): # Private variable self.__balance = balance def deposit(self, amount): if amount > 0: self.__balance += amount return f"Deposit Complete: Balance ${self.__balance}" return "Invalid deposit amount." def get_balance(self): return f"Current Balance: ${self.__balance}" # Example Usage of the Class account = Account(10000) print(account.deposit(5000)) # Outputs 'Deposit Complete: Balance $15000' print(account.get_balance()) # Outputs 'Current Balance: $15000' # Attempt to access private variable directly (results in error) # print(account.__balance) # Raises AttributeError

In this example, __balance is a private variable of the Account class.

If you attempt to access __balance directly from outside the class, an AttributeError will occur.

Instead, you can safely modify or check the value of this variable through the deposit and get_balance methods provided by the class.

Mission
0 / 1

Can a private variable be directly accessed from outside the class?

O
X

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result