To implement a subscriptable object is easy, just implement __getitem__
in this object's class definition.
But now I want to implement a subscriptable class. For example, I want to implement this code:
class Fruit(object):
Apple = 0
Pear = 1
Banana = 2
#________________________________
#/ Some other definitions, \
#\ make class 'Fruit' subscriptable. /
# --------------------------------
# \ ^__^
# \ (oo)\_______
# (__)\ )\/\
# ||----w |
# || ||
print Fruit['Apple'], Fruit['Banana']
#Output: 0 2
I know getattr
can do the same thing, but I feel subscript accessing is more elegant.