2

我如何进行项目访问,即。__getitem__在 Python 2.x 中的类对象上可用?

我试过了:

class B:
    @classmethod
    def __getitem__(cls, key):
        raise IndexError

测试:

B[0]
# TypeError: 'classobj' object has no attribute '__getitem__'
print B.__dict__
# { ... '__getitem__': <classmethod object at 0x024F5E70>}

我如何__getitem__在课堂上工作?

4

1 回答 1

1

正如Martijn Pieters所指出的,人们可能希望在此处为特殊方法查找定义一个元类。

如果您可以使用新型类(或不知道那是什么):

class Meta_B(type):
    def __getitem__(self, key):
        raise IndexError
#

class B(object):
    __metaclass__ = Meta_B
#

测试

B[0]
# IndexError, as expected
于 2014-04-29T16:33:26.830 回答