How data hiding works in Python Classes?

Data hiding in Python uses double underscores before attribute names to make them private or inaccessible from outside the class. This is achieved through name mangling, where Python internally changes the attribute name.

Basic Data Hiding Example

The following example shows how a variable with double underscores becomes hidden ?

class MyClass:
    __hiddenVar = 0
    
    def add(self, increment):
        self.__hiddenVar += increment
        print(self.__hiddenVar)

myObject = MyClass()
myObject.add(3)
myObject.add(8)

# This will cause an error
try:
    print(myObject.__hiddenVar)
except AttributeError as e:
    print(f"Error: {e}")
3
11
Error: 'MyClass' object has no attribute '__hiddenVar'

When we try to access the hidden variable outside the class, Python throws an AttributeError because the variable is not directly accessible.

Accessing Hidden Attributes Using Name Mangling

We can still access hidden attributes using Python's name mangling syntax: _ClassName__attributeName ?

class MyClass:
    __hiddenVar = 12
    
    def add(self, increment):
        self.__hiddenVar += increment
        print(self.__hiddenVar)

myObject = MyClass()
myObject.add(3)
myObject.add(8)

# Access using name mangling
print("Hidden variable value:", myObject._MyClass__hiddenVar)
15
23
Hidden variable value: 23

Data Hiding with Methods

Methods can also be hidden using double underscores ?

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance
    
    def __validate_amount(self, amount):
        return amount > 0
    
    def deposit(self, amount):
        if self.__validate_amount(amount):
            self.__balance += amount
            print(f"Deposited {amount}. New balance: {self.__balance}")
        else:
            print("Invalid amount")

account = BankAccount(1000)
account.deposit(500)

# This will cause an error
try:
    account.__validate_amount(100)
except AttributeError as e:
    print(f"Error: {e}")
Deposited 500. New balance: 1500
Error: 'BankAccount' object has no attribute '__validate_amount'

Key Points

  • Double underscores (__) before attribute/method names trigger name mangling
  • Python internally converts __attribute to _ClassName__attribute
  • This provides privacy by convention, not true encapsulation
  • Hidden attributes can still be accessed using the mangled name
  • Use single underscore (_attribute) for protected members by convention

Conclusion

Data hiding in Python uses name mangling with double underscores to make attributes private by convention. While not truly private, this mechanism discourages direct access from outside the class and helps maintain encapsulation principles.

---
Updated on: 2026-03-24T19:43:04+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements