有没有办法使对象可下标?

use*_*423 4 python oop

我有一个示例类:

class collection:
    def __init__(self, itemArray):
        self.itemArray = itemArray
        self.max = len(itemArray)


    def __iter__(self):
        self.index = 0
        return self

    def __next__(self):
        if self.index < self.max:
            result = self.itemArray[self.index]
            self.index += 1
            return result
        else:
            raise StopIteration()
Run Code Online (Sandbox Code Playgroud)

我的目标是访问变量self.itemArray而不必collection.itemArray从类外部显式使用。我希望能够通过使其成为可迭代对象来循环对象,这就是为什么我有__iter____next__

我想模仿字符串类型使用的行为,即。

stringVar = "randomTextString"
stringVar[indexVal]
Run Code Online (Sandbox Code Playgroud)

尝试使用对象进行此操作是行不通的,因为它会引发 TypeError,因为对象不可下标。

我只需要有人为我指明正确的方向。我查看了 python 文档以寻求解决方案,但似乎没有找到任何东西。

Uri*_*iel 6

覆盖__getitem____setitem__魔法:

def __getitem__(self, idx):
    return self.itemArray[idx]

def __setitem__(self, idx, val):
    self.itemArray[idx] = val
Run Code Online (Sandbox Code Playgroud)