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

Are Python's 'Private' Methods Really Private?

Barbara Streisand
Release: 2024-12-02 22:33:11
Original
492 people have browsed it

Are Python's

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

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

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!

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