Reputation: 145
I have an example class:
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()
My goal is to access the variable self.itemArray
without having to explicitly use collection.itemArray
from outside the class. I want to be able to loop over the object by making it an iterable, which is why I have __iter__
and __next__
.
I want to mimic the behaviour that string types employs, ie.
stringVar = "randomTextString"
stringVar[indexVal]
Attempting this with a object would not work as it will raise a TypeError because objects aren't subscriptable.
I just need someone to point me in the right direction. I looked at the python docs for a solution but I didn't seem to find anything.
Upvotes: 4
Views: 2330
Reputation: 16214
Override the __getitem__
and __setitem__
magics:
def __getitem__(self, idx):
return self.itemArray[idx]
def __setitem__(self, idx, val):
self.itemArray[idx] = val
Upvotes: 8