【发布时间】:2015-03-24 04:39: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')
我们假设 __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'}
问题很简单。我希望只在类内部访问和更改私有变量。
【问题讨论】:
标签: python class oop object private