python中有没有办法从这样的对象中获取数据:
box = BoxWithOranges()
print box['color']
print box['weight']
print box['count']
更符合要求:
for index in range(box['count']):
box[index].eat()
答案 0 :(得分:2)
您必须为您的班级实施__getitem__
和__setitem__
方法。这是使用[]
运算符时将调用的内容。例如,您可以让班级在内部保留dict
class BoxWithOranges:
def __init__(self):
self.attributes = {}
def __getitem__(self, key):
return self.attributes[key]
def __setitem__(self, key, value):
self.attributes[key] = value
演示
>>> box = BoxWithOranges()
>>> box['color'] = 'red'
>>> box['weight'] = 10.0
>>> print(box['color'])
red
>>> print(box['weight'])
10.0