Home > Backend Development > Python Tutorial > How Private Are Python's 'Private' Methods, Really?

How Private Are Python's 'Private' Methods, Really?

Barbara Streisand
Release: 2024-12-11 12:15:11
Original
610 people have browsed it

How Private Are Python's

Python's "Private" Methods: Not As Impenetrable As They Seem

Despite the misconception that Python's "private" methods offer strong encapsulation, a closer examination reveals that they are not truly private. While prefixing a method with double underscores (__myPrivateMethod()) suggests a private scope, it actually creates a method with a modified name.

For instance, the following class demonstrates this behavior:

class MyClass:
    def myPublicMethod(self):
        print('public method')

    def __myPrivateMethod(self):
        print('this is private!!')
Copy after login

When instantiating an object of this class, one would expect to be unable to access the private method:

obj = MyClass()
obj.myPublicMethod()
Copy after login

However, a subsequent dir(obj) call reveals the existence of a magically created method:

dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
Copy after login

Calling this method reveals the "private" data:

obj._MyClass__myPrivateMethod()
Copy after login

This naming convention is employed to prevent subclasses from inadvertently overriding private methods and attributes of their superclasses. However, it does not hinder deliberate access from the outside.

For 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()  # 42
x.bar()  # 21
print(x.__dict__)  # {'_Bar__baz': 21, '_Foo__baz': 42}
Copy after login

In conclusion, Python's "private" methods are not truly private, allowing subclasses to access them. This design choice prioritizes subclassing flexibility over strict encapsulation, but it also necessitates mindful use by developers to maintain code integrity.

The above is the detailed content of How Private Are Python's 'Private' Methods, Really?. 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