如何使私有变量在Python中不可访问? [英] How Do I Make Private Variables Inaccessable in Python?
问题描述
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')
我们假设__engine和__oil变量是私有的,这意味着我无法通过a .__ engine之类的调用来访问它们.但是,我可以使用__dict__变量来访问甚至更改这些变量.
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.
推荐答案
您尝试执行的操作在Python中是不可能的.
What you are trying to do is not possible in Python.
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
这篇关于如何使私有变量在Python中不可访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!