한 클래스의 __getitem__
을 다른 목록의 동일한 인덱스에있는 항목과 합계로 만들고 싶습니다. 오버로드 된 __getitem__ 다른 인수 허용
>>> class Test(list):
def __init__(self):
self.extend([1, 2, 3])
def __getitem__(self, index, other):
return self[index] + other[index]
>>> t = Test()
>>> t2 = [4, 5, 6]
는하지만, 내 두 시도에 오류가 이어질 :
>>> t[5, t2]
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
t[5, t2]
TypeError: __getitem__() missing 1 required positional argument: 'other'
>>> t.__getitem__(5, t2)
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
t.__getitem__(5, t2)
File "<pyshell#17>", line 5, in __getitem__
return self[index] + other[index]
TypeError: __getitem__() missing 1 required positional argument: 'other'
이 __getitem__
여러 인수를 제공 할 수 있습니까? 그렇다면 어떻게? 그렇지 않다면 에뮬레이션 할 수있는 방법이 있습니까?
예상보다 많은 인수를 가지지 않도록 명시 적 색인을 건너 뛰고 시퀀스 압축 풀기 :'index, other = value'를 사용하십시오. 그것은 더 빠릅니다 (파이썬은 값싼'tuple' 패킹과 언 패킹에 최적화되어 있으며 인덱싱에는 덜 사용됩니다). 나는 이것이 이상한 데 동의한다.말로 표현하면 혼란의 위험이 있으므로 추천 할 것입니다. – ShadowRanger
@ShadowRanger 게시물을 편집했습니다. 고맙습니다! – MSeifert