<分区>
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 变量是私有(private)的,这意味着我不能通过像 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'}
问题很简单。我希望仅在类内部访问和更改私有(private)变量。