在python中迭代对象的方法

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()


您必须为类实现__getitem____setitem__方法。这就是使用[]运算符时调用的内容。例如,您可以让类在内部保留一个dict

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