21

What do I need to change to make this work?

class A:
    @staticmethod
    def __getitem__(val):
        return "It works"

print A[0]

Note that I am calling the __getitem__ method on the type A.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Woltan
  • 13,723
  • 15
  • 78
  • 104

2 Answers2

31

When an object is indexed, the special method __getitem__ is looked for first in the object's class. A class itself is an object, and the class of a class is usually type. So to override __getitem__ for a class, you can redefine its metaclass (to make it a subclass of type):

class MetaA(type):
    def __getitem__(cls,val):
        return "It works"

class A(object):
    __metaclass__=MetaA
    pass

print(A[0])
# It works

In Python3 the metaclass is specified this way:

class A(object, metaclass=MetaA):
    pass
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 2
    @ups: metaclasses are specified in a different way in Python3. I've added code to show how, above. – unutbu Sep 02 '13 at 12:22
20

Python 3.7 introduced __class_getitem__.

class A:
    def __class_getitem__(cls, key):
        return "It works"

print(A[0])
Cruise Liu
  • 496
  • 3
  • 9