Why are Python's 'private' methods not actually private?

后端 未结 12 2115
不思量自难忘°
不思量自难忘° 2020-11-22 02:50

Python gives us the ability to create \'private\' methods and variables within a class by prepending double underscores to the name, like this: __myPrivateMethod()

12条回答
  •  不思量自难忘°
    2020-11-22 02:56

    The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from 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}
    

    Of course, it breaks down if two different classes have the same name.

提交回复
热议问题