According to the link you provided, the concept of private elements exists in Python, including private functions that cannot be called from outside their module. However, the example you provided does not demonstrate true encapsulation or privacy in Python.
In Python, there is a naming convention to indicate that a variable or function is intended to be private. By prefixing an identifier with a single underscore, such as _num
, it is a signal to other developers that the identifier should be treated as private and not accessed directly.
However, Python does not enforce strict encapsulation or prevent access to private members. It is still possible to access them from outside the module, as demonstrated in your example with print a.__num
.
The use of double underscores, like __num
, triggers name mangling, which modifies the name to include the class name. This is primarily used to avoid naming conflicts in subclasses but does not provide true privacy.
To achieve a similar effect to private functions or variables in Python, it is recommended to follow the naming conventions and indicate the intended visibility of the elements. By using a single underscore prefix, you communicate to other developers that those elements are intended for internal use and should not be accessed directly from outside the module. However, it is still possible to access them if needed.