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

标签 python magic-methods python-datamodel first-class

<分区>

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

最佳答案

作为pointed out通过 Martijn Pieters , 人们会想为 special methods lookup 定义一个元类在这里。

如果你可以使用新式类(或者不知道那是什么):

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

class B(object):
    __metaclass__ = Meta_B
#

测试

B[0]
# IndexError, as expected

关于python - 如何让 Python 2 的 __getitem__ 在一个类上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23369885/

相关文章:

python - 使用 tf.data.map 将音频文件拆分为 1 秒的音频张量 block ?

php - 在PHP魔术方法上处理 “not found”案例的最佳方法是什么?

python - 哪些数据模型方法实现参数关键字解包?

python - 充当无限序列的对象的 __len__ 的正确返回值

javascript - 使用 PKCS7Padding 在 python 和 Node.js 之间进行 AES 加密

python - (Python 3) 输出问题

php - 将 __set 与数组一起使用已解决,但为什么呢?

PHP - 重载属性的间接修改

Python:重新定义了原始 'object' 类。如何取回 'object' 类?

python - 在Python中应用函数