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