__getitem__ And __len__ Build Custom Sequences

__len__ and __getitem__ alone make len, indexing, membership, and list() work, because Python falls back to the old sequence protocol for iteration.

PythonData Integrity

Code

pythonsnippet
20 lines
class Playlist:
    """__len__ 与 __getitem__ 让实例直接接入序列协议。"""

    def __init__(self, tracks: list[str]) -> None:
        self._tracks = list(tracks)

    def __len__(self) -> int:
        return len(self._tracks)

    def __getitem__(self, index: int) -> str:
        return self._tracks[index]


playlist = Playlist(["intro", "verse", "chorus"])

print(len(playlist))  # __len__
print(playlist[0])  # __getitem__
print(playlist[-1])  # 负索引由内部 list 代理
print("chorus" in playlist)  # 无 __iter__ 时回退到旧式序列迭代
print(list(playlist))  # 同样走 __getitem__

Output

Captured from a sandboxed run of this snippet in the build pipeline.

3
intro
chorus
True
['intro', 'verse', 'chorus']

How it works

getitem And len Build Custom Sequences keeps everything in the class Playlist and the functions __init__, __len__ and __getitem__.

Using it

The main signature reads def __init__(self, tracks: list[str]) -> None

Look for the chorus prefixes when the file runs; they tie each line to its step.

Key statements

def __init__(self, tracks: list[str]) -> None:
    self._tracks = list(tracks)
def __getitem__(self, index: int) -> str:
    return self._tracks[index]
def __len__(self) -> int:
    return len(self._tracks)

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `__init__`, `__len__`, `__getitem__` at load time.