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

后端 未结 12 2129
不思量自难忘°
不思量自难忘° 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 03:02

    With Python 3.4 this is the behaviour:

    >>> class Foo:
            def __init__(self):
                    pass
            def __privateMethod(self):
                    return 3
            def invoke(self):
                    return self.__privateMethod()
    
    
    >>> help(Foo)
    Help on class Foo in module __main__:
    
    class Foo(builtins.object)
     |  Methods defined here:
     |
     |  __init__(self)
     |
     |  invoke(self)
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |
     |  __dict__
     |      dictionary for instance variables (if defined)
     |
     |  __weakref__
     |      list of weak references to the object (if defined)
    
     >>> f = Foo()
     >>> f.invoke()
     3
     >>> f.__privateMethod()
     Traceback (most recent call last):
       File "", line 1, in 
         f.__privateMethod()
     AttributeError: 'Foo' object has no attribute '__privateMethod'
    

    https://docs.python.org/3/tutorial/classes.html#tut-private

    Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.

    Even if the question is old I hope my snippet could be helpful.

提交回复
热议问题