I am getting a weird error when trying to make the getitem method.
My code is:
def __getitem__(self, item):
if (self.shape[0] == 1):
return self.values[item]
else:
x, y = item
return self.twoDim[x][y]
I can't see where my mistake is, when I try
assert my_array[1][0] == 4
I get this error under:
x, y = item
TypeError: cannot unpack non-iterable int object
Any idea what the problem is? Thank for any tips
CodePudding user response:
Doing array[0][1]
is first passing 0
into the __getitem__
function, and then whatever the function returns, it passes [1]
into that function. With your implementation, you cannot do this. You must input a tuple of values in the first __getitem__
function:
class Array:
def __init__(self):
self.shape = (2, 2)
self.values = None
self.twoDim = [[1, 2], [3, 4]]
def __getitem__(self, item):
print(f"{item=}")
if (self.shape[0] == 1):
return self.values[item]
else:
x, y = item
return self.twoDim[x][y]
array = Array()
try:
print(array[1][0]) # item=1
except TypeError:
pass
print("------")
print(array[1, 1] == 4) # item=(1, 1)
# True