문제

Assume I have a class X which has 2 attributes : i and j.

I want to have :

x = X((1,2,3),(2,3,4)) #this would set i to (1,2,3) and j to (2,3,4)

I now want subscripting to work in the following way :

a, b = x[1,2] #a should now be 2 and b should now be 3

At the moment I'm trying this :

    def __getitem__(self, i, j):
        return self.x[i] , self.y[j]

However this keeps giving me the error that getitem takes in exactly 3 arguments but 2 is given (when I try to print out x[1,2] for instance)

도움이 되었습니까?

해결책

Comma is the tuple packing operator. x[1, 2] calls x.__getitem__((1, 2)).

def __getitem__(self, ij):
   i, j = ij
   return self.x[i], self.y[j]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top