Why Python’s Double Underscore Doesn’t Guarantee True Privacy
This article explains Python’s double‑underscore name‑mangling for private attributes, how they can still be accessed via class methods, the pitfalls of attribute shadowing, and why deleting dict entries may raise errors due to CPython’s underlying C implementation.
In Python classes, attributes and methods can be accessed and modified directly through instances.
To hide internal attributes from external access, prefix the variable name with two underscores (__).
When an instance variable starts with __, Python treats it as a private variable that is only accessible inside the class; external code cannot directly access it via the class or instance.
Code example:
Although external code cannot directly access a private attribute, it can be accessed and modified indirectly through class methods.
Class internal methods getname and setname:
Is a double‑underscore private attribute always inaccessible from outside? Actually, it is not:
Python exhibits two interesting phenomena: external variables can shadow class variables, so accessing class attributes via an instance requires caution.
Like regular Python variables, assigning to an instance attribute creates the attribute on the instance if it does not already exist.
However, if a class attribute with the same name exists, this creates a side effect where the instance attribute hides the class attribute.
This behavior persists in Python 3.x.
Example code:
Why does deleting a dict attribute sometimes raise an error?
The reason lies in CPython’s implementation: Python is written in C.
In C there is no native string type; strings are represented as character arrays stored in contiguous memory and are immutable. Any modification creates a new array without altering the original.
In contrast, a dict is stored as a collection of non‑contiguous memory blocks that can be modified in place, so attempting to delete an attribute like f.x in the second example triggers an error.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
