简体   繁体   中英

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?

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. In addition, redefining _internal_sequence = [...] seems to remove the __getitem__ and cause IndexError .

B) This doesn't look as nice as A) and for builtin types it will be slower - see here .

Hence, A is the recommended way of mapping a class's __getitem__ to an internal sequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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