简体   繁体   English

问答:在类中定义__getitem__方法或分配__getitem__

[英]Q&A: Defining __getitem__ method or assigning __getitem__ in classes

Which of the below is the recommended way to do __getitem__ , when it maps to an internal sequence type? __getitem__映射到内部序列类型时,建议使用以下哪种方法?

class A:
    def __init__(self, ...):
        ...
        self._internal_sequence = []

    def __getitem__(self, key):
        return self._internal_sequence[key]

class B:
    def __init__(self, ...):
        ...
        self._internal_sequence = []

    def __getitem__(self, key):
        # I'm pretty sure it won't be this one.
        return self._internal_sequence.__getitem__(key)

class C:
    _internal_sequence = []
    __getitem__ = _internal_sequence.__getitem__

I realised my answer while writing the question, but I'll still post it here so others can benefit. 我在写问题时意识到了答案,但我仍将其张贴在这里,以便其他人受益。

C) This appears to work fine, until you realise the _internal_sequence is a class variable and will retain itself between classes. C)这似乎很好用,直到您意识到_internal_sequence是一个类变量并且将在各个类之间保留自己。 In addition, redefining _internal_sequence = [...] seems to remove the __getitem__ and cause IndexError . 此外,重新定义_internal_sequence = [...]似乎删除了__getitem__并导致IndexError

B) This doesn't look as nice as A) and for builtin types it will be slower - see here . B)看起来不如A)好,对于内置类型,它会更慢-请参见此处

Hence, A is the recommended way of mapping a class's __getitem__ to an internal sequence. 因此,A是将类的__getitem__映射到内部序列的推荐方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM