How Do I Make Private Variables Inaccessable in Python? [duplicate]

二次信任 提交于 2019-12-19 07:35:11

问题


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')

We assume that __engine and __oil variables are private which means I cannot access them through a call like a.__engine. However, I can use __dict__ variable to access and even change those variables.

# 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.


回答1:


What you are trying to do is not possible in 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#private-variables-and-class-local-references




回答2:


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

So, don't write code outside the class that accesses variables starting with __. Use pylint or the like to catch style mistakes like that.



来源:https://stackoverflow.com/questions/28138734/how-do-i-make-private-variables-inaccessable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!