关于类:如何在Python中无法访问私有变量?

How Do I Make Private Variables Inaccessable in Python?

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
7
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')

我们假设"引擎"和"油"变量是私有的,这意味着我不能通过像"引擎"这样的调用访问它们。但是,我可以使用uudict_uuuuuuuuuuuuuuuuuvariable访问甚至更改这些变量。

1
2
3
4
5
6
7
8
# 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'}

问题很简单。我希望只在类内访问和更改私有变量。


The problem is simple. I want private variables to be accessed and changed only inside the class.

所以,不要在访问以__开头的变量的类之外编写代码。使用pylint或类似工具来捕获这样的样式错误。


在Python中,您试图做的是不可能的。

"Private" instance variables that cannot be accessed except from inside an object don’t exist in Python.

https://docs.python.org/2/tutorial/classes.html私有变量和类本地引用