如何使 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__ 变量来访问甚至更改这些变量。
# 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'}
问题很简单。我只想访问和更改私有变量 inside the class.
您要执行的操作在 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
The problem is simple. I want private variables to be accessed and changed only inside the class.
因此,不要在 class 之外编写访问以 __
开头的变量的代码。使用 pylint 之类的工具来捕获这样的样式错误。
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__ 变量来访问甚至更改这些变量。
# 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'}
问题很简单。我只想访问和更改私有变量 inside the class.
您要执行的操作在 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
The problem is simple. I want private variables to be accessed and changed only inside the class.
因此,不要在 class 之外编写访问以 __
开头的变量的代码。使用 pylint 之类的工具来捕获这样的样式错误。