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 变量是私有的,这意味着我无法通过像 .__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班上。
问题很简单。我希望私有变量只能在类内部访问和更改。
因此,不要在类之外编写访问以开头的变量的代码__
。使用 pylint 之类的工具来捕获类似的风格错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)