Python 有没有办法使对象可下标?
我有一个例子:Python 有没有办法使对象可下标?,python,oop,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 <
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()
使用对象尝试此操作将不起作用,因为它将引发TypeError,因为对象不可下标
我只需要有人给我指出正确的方向。我查看了python文档以寻找解决方案,但似乎没有找到任何解决方案。覆盖
\uuu getitem\uuuuuuu
和\uuuuu setitem\uuuuuu
magics:
def __getitem__(self, idx):
return self.itemArray[idx]
def __setitem__(self, idx, val):
self.itemArray[idx] = val
Override
\uuu getitem\uuuu
我很惊讶没有找到这个问题的好副本。我确实找到了一些人,他们已经知道如何做到这一点,并希望在此基础上进行扩展;但也许将来我会在这里提到其他问题。因为它的价值:如果你提供\uuu getitem\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
以及\uuuuuuu len\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,标准库可以为您生成\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
和\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。只需执行objCollection,append(“val”)
。有没有办法做到这一点?@user5423取决于您的目标-如果您只想展开列表,请使集合
继承自列表
,并为每个自定义函数调用其源函数super()。函数(args…
)。你甚至不需要你实现的其他方法。请注意,list
的\uuuuu init\uuuuu
签名与您的签名相同,itemArray
默认为空列表。@user5423请参阅我上面所述的内容
def __getitem__(self, idx):
return self.itemArray[idx]
def __setitem__(self, idx, val):
self.itemArray[idx] = val