Marissa S. answered 07/04/19
Python & C/C++ Tutor!
Single leading underscore ( _foo )
----------------------------------------------------------------------
This naming convention is intended to tell the programmer that the attribute, function, or method is private or used for internal use. This is a convention that is not enforced by the python interpreter but rather a way to help organize the code for the programmer and communicate where the object should be used:
The leading underscore tells the programmer that self._foo should only be referenced within the class. However, there is nothing stopping the programmer from accessing the attribute outside of the class, for example:
Double leading underscores ( __foo ):
-----------------------------------------------------------------------
Double underscores in front of an attribute has meaning to a Python interpreter. The interpreter enforces "name mangling", which is a way for the interpreter to rename the attribute by adding the class name to the front of a double leading underscore attribute. This can be observed by looking at the object's attributes:
The "dir()" function returns a list of the object's attributes. As demonstrated from the list, the attribute "foo" is in the list but "__foo" is not. "__foo" got renamed to '_Foo_foo' which is at the beginning of the list. This naming convention also affects the programmer's access to the attribute. Unlike attributes with a single leading underscore, double leading underscore attributes cannot be accessed outside of the class.
The attribute can still be accessed externally by using the renamed variable name "_Foo__foo", however, this is generally not advised. The program can cause errors if a class gets renamed. If needed, the safest way to access the attribute would be through a class method or accessed internally. (Name mangling also applies to methods but does not apply to variables or functions that are just within a module).