1 def checkIndex(key):
2 if not isinstance(key, (int,)):
3 raise TypeError
4 if key < 0:
5 raise IndexError
6
7 class ArithmeticSequence:
8 def __init__(self, start = 0, step = 1):
9 self.start = start
10 self.step = step
11 self.changed = {}
12
13 def __getitem__(self, key):
14
15 checkIndex(key)
16
17 print('__getitem__')
18
19 try:
20 return self.changed[key]
21 except KeyError:
22 return self.start + key * self.step
23
24 def __setitem__(self, key, value):
25
26 checkIndex(key)
27
28 print('__setitem__')
29
30 self.changed[key] = value
31
32
33 s = ArithmeticSequence(1, 2)
34 print(s[4])
35 s[4] = 2
36 print(s[4])
37 print(s[5])
38 s[3] = 100
39 print(s[3])
40 s.__setitem__(100, 3)
41 print(s.__getitem__(100))
输出:
>>>
__getitem__
9
__setitem__
__getitem__
2
__getitem__
11
__setitem__
__getitem__
100
__setitem__
__getitem__
3
posted on 2013-05-21 22:03
unixfy 阅读(234)
评论(0) 编辑 收藏 引用