In this lesson, you will learn how to use double underscores to protect your object's internal implementation details from being accidentally modified or accessed from outside the class.
Understanding Name Mangling
In Python, all object attributes are technically "public." While developers often use a single underscore (e.g., _internal) as a polite convention to signal that an attribute should be treated as private, it doesn’t actually prevent anyone from accessing it.
To provide a stronger form of protection, Python offers name mangling. When you prefix an attribute name with two underscores (e.g., __hidden), Python automatically renames the attribute internally to include the class name. This makes it difficult to accidentally access the attribute from outside the class scope.
How It Works
Consider a BankAccount class where we want to keep the balance secure:
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # Name mangling happens here
def get_balance(self):
return self.__balance
account = BankAccount("Alice", 1000)
# This works fine
print(account.get_balance())
# This will raise an AttributeError!
# print(account.__balance)
Behind the scenes, Python renames __balance to _BankAccount__balance. Because of this renaming, if you try to access account.__balance directly from your main program, Python won't find it.
Why Use It?
Name mangling is not designed for "security" in the cryptographic sense—someone determined can still access the mangled name if they really want to. Instead, it is an encapsulation tool. It protects your internal variables from being accidentally overridden by subclasses or other parts of a large program that might use the same variable names. It forces external code to go through your defined methods (like get_balance()) to interact with the internal state, ensuring your object's data remains consistent and controlled.
Key Takeaway: By using double underscores, you trigger Python’s name mangling mechanism, which helps prevent accidental external access to internal data and ensures that your class implementation remains private and robust.