Data Hiding with Name Mangling __var

Learn how to hide data in Python classes using name mangling with double underscores for better encapsulation.
Data Hiding in Python with Name Mangling
Python does not enforce strict access restrictions to class variables and methods like private or protected modifiers in other languages. However, it uses a technique called name mangling to discourage direct access to variables that are meant to be private.
What is Name Mangling?
Name mangling in Python means that any identifier with two leading underscores (e.g., __var
) and at most one trailing underscore will be transformed to include the class name as a prefix. This makes it harder to accidentally override or access such variables from outside the class.
Why Use Name Mangling?
This feature is useful for data hiding, encapsulation, and avoiding name conflicts in subclasses. It allows developers to communicate intent that certain attributes are not part of the class’s public API and should not be accessed directly.
Basic Example of Name Mangling
Let’s create a simple class to demonstrate name mangling:
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age # Private attribute
def get_age(self):
return self.__age
p = Person(\\"John\\", 30)
print(p.name) # John
print(p.get_age()) # 30
# Direct access will fail
# print(p.__age) # AttributeError
The __age
attribute is not directly accessible using p.__age
. Python mangles it to _Person__age
.
Accessing Mangled Attributes (Not Recommended)
Though name mangling hides the attribute, it can still be accessed with its mangled name:
print(p._Person__age) # 30
This is generally discouraged as it breaks encapsulation.
Conclusion
Using double underscores and name mangling helps protect your class’s internal state. While it is not true private protection, it is a useful convention for cleaner and safer code.
Subscribe to Our YouTube for More
https://blog.arashtad.com/updates/data-hiding-with-name-mangling-__var/?feed_id=13458&_unique_id=689c180230b23
Comments
Post a Comment