在python中迭代对象的方法

时间:2015-10-01 12:17:16

标签: python object properties

python中有没有办法从这样的对象中获取数据:

box = BoxWithOranges()
print box['color']
print box['weight']
print box['count']

更符合要求:

for index in range(box['count']):
    box[index].eat()

1 个答案:

答案 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