How to write a static python getitem method?

我的梦境 提交于 2019-12-21 03:54:17

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/6187932/how-to-write-a-static-python-getitem-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!