如何使Python无法访问私有变量?

Erd*_*ray 5 python oop private class object

class Car(object):
    def __init__(self, color, engine, oil):
        self.color = color
        self.__engine = engine
        self.__oil = oil

a = Car('black', 'a cool engine', 'some cool oil')
Run Code Online (Sandbox Code Playgroud)

我们假设__engine和__oil变量是私有的,这意味着我无法通过a .__ engine之类的调用来访问它们。但是,我可以使用__dict__变量来访问甚至更改这些变量。

# Accessing
a.__dict__
{'_Car__engine': 'a cool engine', 'color': 'black', '_Car__oil': 'some cool oil'}

# Changing
a.__dict__['_Car__engine'] = "yet another cool engine"
a.__dict__
{'_Car__engine': 'yet another cool engine', 'color': 'black', '_Car__oil': 'some cool oil'}
Run Code Online (Sandbox Code Playgroud)

问题很简单。我希望仅内部访问和更改私有变量。

Vas*_*eev 2

你想要做的事情在 Python 中是不可能的。

\n\n
\n

Python 中不存在 \xe2\x80\x9cPrivate\xe2\x80\x9d 实例变量,这些变量只能从对象内部访问。

\n
\n\n

https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references

\n