Unlike some other programming languages like Java and C++, Python doesn't officially support the notion of "private" variables. However, Python does have a naming convention that is used to indicate a variable should be treated as private and should not be accessed directly. This is achieved by prefixing the variable name with a double underscore (__
), and this is the correct answer in the question posed.
Here is an example:
class MyClass:
def __init__(self):
self.__private_variable = 0
In the code above, __private_variable
is considered a "private" member variable of the MyClass
class, thanks to the double underscore prefix.
It's important to remember that this is merely a convention and Python doesn't prevent access to these variables. The double underscore prefix causes the Python interpreter to 'mangle' the name of the variable in a way that makes it more difficult to access unintentionally.
For example, trying to access the variable directly might look like this:
obj = MyClass()
print(obj.__private_variable) # Raises an AttributeError
Attempting to access __private_variable
in the way shown above will raise an AttributeError
. Its name gets mangled into _MyClass__private_variable
, and can still be accessed using this mangled name. However, this is not good practice.
print(obj._MyClass__private_variable) # Prints '0'
This naming convention is a way of indicating to other programmers (including your future self) that a variable or method should not be accessed directly. Like many Python practices, it is based on the concept of consent: "we're all adults here," and if a developer chooses to ignore the convention, they must deal with the potential consequences on their own.
If the aim is to indicate that a variable is "private" and should not be modified directly, but should still be readable (as in a read-only property), a single underscore can be used instead. This indicates the variable or method is "protected" and should not be accessed directly, although Python does not enforce this rule like it would in other languages such as Java.
Despite Python's flexible approach towards private variables, it's considered good practice to respect these naming conventions to maintain the integrity of your classes and objects.