Python's 'Private' Methods: Unveiling the Myth of Encapsulation
Contrary to its name, Python's 'private' methods are not entirely private. While prepending double underscores to a method name (e.g., __myPrivateMethod()) creates the illusion of privacy, Python exposes these methods through a dynamically generated method with a modified name.
Consider the following code:
class MyClass: def myPublicMethod(self): print('public method') def __myPrivateMethod(self): print('this is private!!') obj = MyClass()
Calling obj.myPublicMethod() successfully invokes the public method. However, attempting to call obj.__myPrivateMethod() results in an AttributeError.
Delving deeper into the matter with dir(obj), we uncover a new method:
dir(obj) # Output: ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
This dynamically generated method, named _MyClass__myPrivateMethod, maintains the reference to the supposedly private method.
Despite the name scrambling, the purpose is not to prevent deliberate external access. Rather, it ensures that subclasses do not accidentally override private methods and attributes of 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) x = Bar() x.foo() # Output: 42 x.bar() # Output: 21 print(x.__dict__) # Output: {'_Bar__baz': 21, '_Foo__baz': 42}
The subclasses can still access the overridden private attribute or method through the modified name.
In summary, Python's 'private' methods are not truly private in the sense of object-oriented programming principles. They are merely a mechanism to prevent accidental overrides, but they offer no protection against deliberate external access.
The above is the detailed content of Is Python's 'Private' Method Encapsulation a Myth?. For more information, please follow other related articles on the PHP Chinese website!