Data hiding in Python
What is the difference between _var and __var :
In Python, a single leading underscore before a variable or method name is used to indicate that it is intended to be a non-public or "internal" member of the class. It's more of a convention rather than a strict rule and can be accessed from outside the class. For example, if a variable is named _x, it's intended to be used within the class and is not part of the class's public API. However, it can still be accessed from outside the class using object._x.
On the other hand, double leading underscores before a variable or method name (e.g. __var) indicate name mangling or "private name" behavior in Python. When a class attribute is preceded by two underscores, its name gets "mangled" by the interpreter by adding _classname before the attribute name, where classname is the name of the class. This is done to avoid naming collisions when a class has a parent class and a child class, and both classes have attributes with the same name.
This name mangling also prevents external code from accessing the attribute directly, without going through the class's methods. However, it is still possible to access a double underscore attribute from outside the class using its mangled name, which can be obtained by prefixing it with _classname, as shown in the previous example. It's worth noting that using double underscore attributes for data hiding purposes is not considered a good practice in Python. Instead, a single underscore is usually used to indicate that an attribute is intended to be private.