-4

Is there a way in python to get data from object like this:

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

And more compliant:

for index in range(box['count']):
    box[index].eat()
Jury
  • 1,227
  • 3
  • 17
  • 30

1 Answers1

2

You'd have to implement the __getitem__ and __setitem__ methods for your class. That is what would be invoked when you used the [] operator. For example you could have the class keep a dict internally

class BoxWithOranges:
    def __init__(self):
        self.attributes = {}

    def __getitem__(self, key):
        return self.attributes[key]

    def __setitem__(self, key, value):
        self.attributes[key] = value

Demo

>>> box = BoxWithOranges()
>>> box['color'] = 'red'
>>> box['weight'] = 10.0
>>> print(box['color'])
red
>>> print(box['weight'])
10.0
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • I think the key is it needs to take an index or a dictionary key. I wonder if that means in `__getitem__` and `__setitem__` distinguishing between integers and strings. – neil Oct 01 '15 at 13:08