Way to iterate though object in python
在python中,有没有一种方法可以从这样的对象中获取数据:
1 2 3 4 | box = BoxWithOranges() print box['color'] print box['weight'] print box['count'] |
更合规:
1 2 | for index in range(box['count']): box[index].eat() |
您必须为类实现
1 2 3 4 5 6 7 8 9 | class BoxWithOranges: def __init__(self): self.attributes = {} def __getitem__(self, key): return self.attributes[key] def __setitem__(self, key, value): self.attributes[key] = value |
演示
1 2 3 4 5 6 7 | >>> box = BoxWithOranges() >>> box['color'] = 'red' >>> box['weight'] = 10.0 >>> print(box['color']) red >>> print(box['weight']) 10.0 |