Python Private Attributes and Functions
In many programming languages, there is the concept of "private" class attributes - variables and functions that cannot be accessed by anyone outside of the class. In Python, all variables and functions defined by a class are always public. Therefore, the convention is to use an underscore before the variable or function name to indicate that it is private.
Example
Python
Copy Code
class ClassWithPrivateFields(): def __init__(self): self._iAmPrivate = 5 # I should be private myClass=ClassWithPrivateFields() print(f'Oops, accessing a private field! It has the value {myClass._iAmPrivate}')
Output
Oops, accessing a private field! It has the value 5
Notes
As the example illustrates, you can definitely read/write private fields (and functions!), so the only thing stopping you is knowing that a field or function preceded with an underscore should not be used by code outside of the class defining that field or function. Some IDEs can be configured to not show objects whose name is begins with an underscore.