In this post, we will learn about data hiding in Python, the basics of private and public variables, concept of name mangling, why data hiding is important, and whether Python allows us to create true private variables, with detailed explanations and examples. So, let’s get started!
👉 Prerequisite for this post: You should have a basic understanding of OOP (Object-Oriented Programming).
What is Data Hiding?
Data hiding is a concept in programming where certain information (data) inside an object is kept private. This means that the data cannot be accessed or modified directly from outside the object. Instead, specific methods (functions inside the object) control how the data is accessed or changed.
This helps to protect sensitive data from being accidentally changed or misused by someone who doesn’t fully understand how the object works.
But before implementing data-hiding concepts, it is important to understand variables in Python classes. So, let’s understand that first.
Understanding Variables in Python Classes
When we create an object in Python, we often store data inside it using variables. These variables can be public (available for everyone to access) or private (hidden from outside access).
Example of a Public Variable:
class Car:
def __init__(self, speed):
self.speed = speed # Public variable
# Creating an object
car = Car(100)
# Accessing the public variable directly
print(car.speed) # Output: 100
Here, speed
is a public variable because we can access and modify it directly from outside the class.
Public variables can be accessed and modified outside of the class, but to understand data-hiding concepts, it is important to focus on private variables because they are essential for achieving data hiding. So, let’s dive deeper into it.
What are Private Variables?
In Python, private variables are created by adding two underscores (__
) before the variable name. This tells Python that the variable is private and should not be accessed directly from outside the class.
Example of a Private Variable:
class Car:
def __init__(self, speed):
self.__speed = speed # Private variable
# Creating an object
car = Car(100)
# Trying to access the private variable directly (this will fail)
print(car.__speed) # This will raise an AttributeError
In this example, __speed
is a private variable. If you try to access it directly, Python will throw an error because private variables are hidden.
From the above explanation, you might think that once a private variable is created, it is impossible to access it from outside the class. However, this is not the case. To understand whether it is truly private and whether we can modify it, you need to learn how Python handles private variables. So, let’s dive into that.
How Does Python Handle Private Variables?
Now, here’s where things get interesting. Python doesn’t strictly prevent access to private variables. Instead, it uses a trick called name mangling to make it harder (but not impossible) to access private variables from outside the class.
What is Name Mangling?
Name mangling is Python’s way of internally changing the name of a private variable to make it difficult to access directly.
For example, if you create a private variable called __speed
in a Car
class, Python will rename it to something like _Car__speed
behind the scenes. This makes it harder to access, but not impossible.
Example of Name Mangling:
class Car:
def __init__(self, speed):
self.__speed = speed # Private variable
# Creating an object
car = Car(100)
# Accessing the private variable using the mangled name
print(car._Car__speed) # Output: 100
In this example, we can still access the private variable using its mangled name (_Car__speed
). But doing this breaks the rule of data hiding, and it’s not recommended unless you know exactly what you’re doing.
After realizing that private variables are not truly private, you might wonder what the importance of name mangling is if the variable is still accessible even after its name is mangled. So, let’s find out.
Why Does Python Use Name Mangling?
Python uses name mangling to signal that a variable is private and should not be accessed directly. Name mangling doesn’t enforce strict privacy, but it’s designed to:
- Make accidental access difficult: If someone tries to access the private variable directly, they will get an error. This helps prevent mistakes.
- Signal privacy: Name mangling is a way to tell other developers, “Hey, this variable is private. You shouldn’t touch it.”
Why Do We Use Private Variables?
Even though Python doesn’t enforce strict privacy, using private variables has important benefits:
Protecting Sensitive Data:
Private variables help you protect important or sensitive data. For example, in a banking application, you don’t want someone to accidentally change the balance directly.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def deposit(self, amount):
if amount > 0:
self.__balance += amount # Controlled access to the balance
def get_balance(self):
return self.__balance
In this example, the private variable __balance
is hidden from outside access. You can only change it through the deposit
method, which ensures that no one can accidentally set a negative balance.
Preventing Accidental Changes:
Sometimes, other parts of your code (or other developers) might accidentally change a variable’s value. By marking a variable as private, you make sure that no one can change it directly by mistake.
Encapsulation:
Private variables are a key part of encapsulation, which means hiding the internal details of an object and only exposing the necessary parts. This makes your code more organized and easier to maintain.
Signaling to Other Developers:
When other programmers see a variable with double underscores (__
), they know that this variable is meant to be private and should not be accessed directly. This makes the code clearer and easier to understand.
Conclusion
Data hiding is an important concept in Python, especially when you want to protect sensitive information and prevent accidental errors. By using private variables and name mangling, Python allows you to signal to other developers (and yourself) that certain data should not be accessed or modified directly.
Even though Python doesn’t enforce strict privacy, using private variables is a best practice for making your code more secure, reliable, and easier to maintain. It helps you control how data is accessed, prevents mistakes, and makes your code clearer for others to understand.
That’s all about data hiding in Python. Thank you for reading this article, and see you soon in the next one. Meanwhile, if you really want to learn Python, click here.