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
.
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
.
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 usuallytype
. So to override__getitem__
for a class, you can redefine its metaclass (to make it a subclass oftype
):In Python3 the metaclass is specified this way: