How to write a static python getitem method?

前端 未结 2 551
走了就别回头了
走了就别回头了 2021-01-02 01:38

What do I need to change to make this work?

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

print A[0]

No

相关标签:
2条回答
  • 2021-01-02 02:25

    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
    
    0 讨论(0)
  • 2021-01-02 02:32

    Python 3.7 introduced __class_getitem__.

    class A:
        def __class_getitem__(cls, key):
            return "It works"
    
    print(A[0])
    
    0 讨论(0)
提交回复
热议问题