답변:
이 __getitem__방법 을 사용해야합니다 .
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
그리고 값을 설정하려면 __setitem__메소드 도 구현해야합니다 . 그렇지 않으면 이런 일이 발생합니다.
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
완전히 오버로드하려면 __setitem__and __delitem__메소드도 구현해야 합니다.
편집하다
나는 거의 잊어 버렸다 ...리스트를 완전히 에뮬레이션하려면 또한 필요합니다 __getslice__, __setslice__ and __delslice__.
http://docs.python.org/reference/datamodel.html에 모두 문서화되어 있습니다.
__getitem__방법을 찾고 있습니다. http://docs.python.org/reference/datamodel.html 섹션 3.4.6을 참조 하십시오 .
__getslice__,__setslice__` 및__delslice__' have been deprecated for the last few releases of ver 2.x (not sure exactly when), and are no longer supported in ver 3.x. Instead, use__getitem__.__setitem__` 및__delitem__' and test if the argument is of type슬라이스, i.e.:경우 isinstance (ARG, 슬라이스) : ...