ชื่อของวิธีการแทนที่[]ผู้ประกอบการ (สัญกรณ์ห้อย) สำหรับชั้นเรียนในงูหลามคืออะไร?
ชื่อของวิธีการแทนที่[]ผู้ประกอบการ (สัญกรณ์ห้อย) สำหรับชั้นเรียนในงูหลามคืออะไร?
คำตอบ:
คุณจำเป็นต้องใช้วิธีการ__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__และ__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 (หาเรื่องชิ้น): ...