Home >Backend Development >Python Tutorial >Are Python's 'Private' Methods Really Private?
Why Python's 'Private' Methods Are Not Actually Private
Despite the double underscore prefix commonly used to denote 'private' methods in Python, these methods remain accessible to users through a slightly different naming convention.
The Python interpreter renames these 'private' methods to "_ClassName__MethodName". Thus, the purportedly 'private' method "__myPrivateMethod()" can be invoked as "_MyClass__myPrivateMethod()".
This name scrambling is not intended as a form of encapsulation or to prevent outside access. Instead, it serves to ensure that subclasses do not unintentionally override the 'private' methods of their superclasses.
Consider the following example:
class Foo(object): def __init__(self): self.__baz = 42 def foo(self): print(self.__baz) class Bar(Foo): def __init__(self): super(Bar, self).__init__() self.__baz = 21 def bar(self): print(self.__baz)
When we create an instance of Bar and call both foo() and bar(), we see the following output:
x = Bar() x.foo() 42 x.bar() 21
As evidenced by the output, the subclass successfully overrides the value of __baz without affecting the superclass's 'private' attribute. Moreover, accessing x.__dict__ reveals that both versions of the __baz attribute coexist within the subclass instance.
While this name scrambling may deter accidental overrides, it does not prevent intentional access to 'private' methods from external sources. Consequently, Python's 'private' methods are not truly private and should not be relied upon for encapsulation.
The above is the detailed content of Are Python's 'Private' Methods Really Private?. For more information, please follow other related articles on the PHP Chinese website!