Простой пример __getitem__ и __setitem__

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# -*- coding: utf-8 -*-
class MyArray():
def __init__(self):
self._range = range(5, 10)
def __getitem__(self, key):
return self._range[key]
def __setitem__(self, key, value):
self._range[key] = value
if __name__ == "__main__":
f = MyArray()
print f[2]
f[2] = 0
print f[2]