Skip to main content
 首页 » 编程设计

python之如何让 Python 2 的 __getitem__ 在一个类上工作

2025年05月04日10rubylouvre

<分区>

如何进行项目访问,即。 __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__ 在类本身上工作?