
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Private Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Namedtuple
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Multiple Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Warnings
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python - Private Variables
Python is an object-oriented programming language that allows you to create classes and objects. Encapsulation is one of the core principles of OPPs. To achieve encapsulation, we use private variables and methods. In this chapter, we will discuss private variables in Python and how to use them.
Following topics will be covered in this chapter −
- What are Private Variables?
- Defining Private Variables in Python
- Name Mangling for Private Variables
- Private Methods in Python
- Real World Example of Private Variables
- Public vs Protected vs Private Variables
What are Private Variables?
Private variables are a special type of variable that is only accessible within the class they are defined in. Means, they are not directly accessible from outside the class or from any subclass. This is done to protect the data and ensure that it is not modified or accessed by unauthorized code snippets.
Only direct access is restricted. We can define a public method to access the private variable from outside the class, it is called a getter method. Similarly, we can use a setter method to modify the value of a private variable from outside the class.
The image shows how Private variables are different from Public and Protected variables.

- Public Variables: Public variables are accessible from anywhere, both inside and outside the class. In the image, a public place is considered as an analogy for public variables as they can be accessed by anyone.
- Protected Variables: Protected variable can be accessed within the class and its subclasses. In the image, a private domicile is considered as an analogy for protected variables as they can be accessed by family members (subclasses) but not by outsiders.
- Private Variables: Private variables are only accessible within the class they are defined in. In the image, a vault is considered as an analogy for private variables as they can only be accessed by the owner (the class itself) and not by anyone else.
Defining Private Variables in Python
In Python, private variables are defined by adding a double underscore (__) before the variable name. Unlike other programming languages like Java or C++, Python does not have strict access modifiers like public, private, or protected. So, the double underscore is a convention used to indicate that a variable is private. Similarly, a single underscore (_) is used to indicate that a variable is protected.
Example
The code below shows how to define a private variable and access it using a public method.
class MyClass: def __init__(self): self.__private_var = "I am Private" def show_private(self): return self.__private_var obj = MyClass() # print(obj.__private_var) # ✗ AttributeError print(obj.show_private()) # ✓ Access through method
We have commented out the direct access to the private variable (Uncommenting it will raise an AttributeError). So, the output of the above code will be −
I am Private
Name Mangling for Private Variables
In Python, private variables are not truly private. They can still be accessed from outside the class using a technique called name mangling. That is, when you create a private variable using a double underscore (__var), Python internally changes its name to _ClassName__var. Now, you can access the private variable using this mangled name. Let's see an example to understand this better.
class MyClass: def __init__(self): self.__private_var = "I am Private" def show_private(self): return self.__private_var obj = MyClass() # Accessing private variable using name mangling print(obj._MyClass__private_var) # ✓ Access using name mangling
The output of the above code will be −
I am Private
Private Methods in Python
Similar to private variables, we can also define private methods in Python. Private methods are methods that are only accessible within the class they are defined in. They are not accessible from outside the class or from any subclass. To define a private method, we use a double underscore (__) before the method name.
class MyClass: def __init__(self): self.__private_var = "I am Private" def __private_method(self): return "This is a private method" def show_private(self): return self.__private_var + " and " + self.__private_method() obj = MyClass() print(obj.show_private()) # ✓ Access through method # print(obj.__private_method()) # ✗ AttributeError print(obj._MyClass__private_method()) # ✓ Access using name mangling
The output of the above code will be −
I am Private and This is a private method This is a private method
Real World Example of Private Variables
Consider a banking application where we have a class called BankAccount. This class has private variables for the account number and balance. We will define public methods to deposit, withdraw, and check the balance. We need to ensure that balance cannot be directly modified outside the class, but can only be changed through deposit and withdraw methods.
The code below demonstrates this concept.
class BankAccount: def __init__(self, account_number, balance): self.__account_number = account_number # Private self.__balance = balance # Private def deposit(self, amount): if amount > 0: self.__balance += amount return self.__balance def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount return self.__balance def get_balance(self): return self.__balance account = BankAccount("12345", 1000) # Direct access will fail try: account.__balance += 500 # ✗ AttributeError except AttributeError: print("Direct access to private variable failed!!!") # Access using methods print("Your account balance is: ", account.get_balance()) # ✓ 1000 account.deposit(500) print("Your account balance after deposit is: ", account.get_balance()) # ✓ 1500
The output of the above code will be −
Direct access to private variable failed!!! Your account balance is: 1000 Your account balance after deposit is: 1500
Public vs Protected vs Private Variables
Here is a tabular comparison of Public, Protected, and Private variables in Python −
Feature | Public Variables | Protected Variables | Private Variables |
---|---|---|---|
Definition | Variables that can be accessed from anywhere. | Variables that can be accessed within the class and its subclasses. | Variables that can only be accessed within the class they are defined in. |
Syntax | int var | int _var | int __var |
Security | Least secure | Moderately secure | Most secure |
Example | int age = 25 | int _age = 25 | int __age = 25 |
Conclusion
In this chapter, we learned about private variables in Python and how to use them to achieve encapsulation. We also discussed name mangling, how private methods work, getters and setters. The name mangling technique allows us to access private variables and methods from outside the class, but it is not recommended to use it as it breaks the encapsulation principle.