Home > Backend Development > Python Tutorial > Is Python's 'Private' Method Encapsulation a Myth?

Is Python's 'Private' Method Encapsulation a Myth?

Mary-Kate Olsen
Release: 2024-12-05 19:16:11
Original
869 people have browsed it

Is Python's

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()
Copy after login

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']
Copy after login

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}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template