How to write a static python getitem method?

前端 未结 2 567
走了就别回头了
走了就别回头了 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:32

    Python 3.7 introduced __class_getitem__.

    class A:
        def __class_getitem__(cls, key):
            return "It works"
    
    print(A[0])
    

提交回复
热议问题