How to implement a subscriptable class in Python (subscriptable class, not subscriptable object)?

Add something like this to your class:

class Fruit(object):
     def __init__(self):
         self.Fruits = {"Apple": 0, "Pear": 1, "Banana": 2}
     def __getitem__(self, item):
         return self.Fruits[item]

Seems to work by changing the metaclass. For Python 2:

class GetAttr(type):
    def __getitem__(cls, x):
        return getattr(cls, x)

class Fruit(object):
    __metaclass__ = GetAttr

    Apple = 0
    Pear = 1
    Banana = 2

print Fruit['Apple'], Fruit['Banana']
# output: 0 2

On Python 3, you should use Enum directly:

import enum

class Fruit(enum.Enum):
    Apple = 0
    Pear = 1
    Banana = 2

print(Fruit['Apple'], Fruit['Banana'])
# Output: Fruit.Apple, Fruit.Banana
print(Fruit['Apple'].value, Fruit['Banana'].value)
# Output: 0 2

just expanding on @Luis Kleinwort ' s answer, if you want to do this for all class attributes,


>>>fruitsdict = {'apple':0, 'banana':1}

>>>class Fruits(object):
    def __init__(self, args):
        for k in args:
            setattr(self, k, args[k])

    def __getitem__(self, item):
         return getattr(self, item)

>>>fruits = Fruits(fruitsdict)

>>>print(fruits.apple)
0
>>>print(fruits['apple'])
0

Tags:

Python