programing

Python에서 [] 연산자를 재정의하는 방법

luckcodes 2022. 12. 27. 22:09

Python에서 [] 연산자를 재정의하는 방법

를 덮어쓰는 메서드의 이름은 무엇입니까?[]연산자(밑줄 표기법)는 Python의 클래스에 사용할 수 있습니까?

방법을 사용해야 합니다.

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6

값을 설정하는 경우 메서드도 구현해야 합니다.그렇지 않으면 다음과 같이 됩니다.

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'

완전히 과부하시키려면 다음 명령어를 실장할 필요도 있습니다.__setitem__그리고.__delitem__방법들.

편집하다

거의 잊어버릴 뻔했어...목록을 완전히 에뮬레이트하려면__getslice__, __setslice__ and __delslice__.

모두 http://docs.python.org/reference/datamodel.html에 기재되어 있습니다.

찾고 있는 것은__getitem__방법.http://docs.python.org/reference/datamodel.html, 섹션 3.4.6을 참조하십시오.

언급URL : https://stackoverflow.com/questions/1957780/how-to-override-the-operator-in-python