How to Use Private Variables in a Class
Private variables
are special attributes that can only be accessed from within the class in which they are defined.
They help protect important data from being modified externally and support the principle of encapsulation.
In Python, private variables are indicated by adding two leading underscores (__
) to the variable name.
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.
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
.
Attempting to access __private_vardirectly
from outside the class (e.g.,obj.__private_var
) will raise an AttributeError
.
By restricting access to private variables through class methods, objects can safeguard internal data and maintain control over how it is accessed or modified.
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.
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' # Attempting to access a private variable directly will result in an 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.
Can a private variable be directly accessed from outside the class?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result