Câu trả lời:
Bạn cần sử dụng __getitem__phương pháp .
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
Và nếu bạn sẽ thiết lập các giá trị, bạn cũng sẽ cần thực hiện __setitem__phương pháp , nếu không điều này sẽ xảy ra:
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
Để quá tải nó, bạn cũng cần phải thực hiện __setitem__và __delitem__các phương thức.
biên tập
Tôi gần như quên mất ... nếu bạn muốn mô phỏng hoàn toàn một danh sách, bạn cũng cần __getslice__, __setslice__ and __delslice__.
Có tất cả tài liệu trong http://docs.python.org/reference/datamodel.html
Bạn đang tìm kiếm __getitem__phương pháp. Xem http://docs.python.org/reference/datamodel.html , phần 3.4.6
__getslice__,__setslice__` và__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__` và__delitem__' and test if the argument is of typelát, i.e.:nếu isinstance (arg, lát): ...