python基础教程——9.3成员访问

模拟映射类(Dict, List)

1
""" 2 Created on Tue May 22 23:10:37 2018 3 4 @author: biok 5 """ 6 7 def checkIndex(key): 8 """ 9 所给的键是能接受的索引吗? 10 11 为了能被接受,键应该是一个非负的整数。如果他不是整数,会引发TypeError;如他是负数 12 则会引起IndexError(因为序列是无限长的)。 13 """ 14 if not isinstance(key, int): raise TypeError 15 if key<0: raise IndexError 16 17 class ArithmeticSequence: 18 def __init__(self, start=0, step=1): 19 """ 20 初始化算数序列 21 22 起始值——序列中的第一个值 23 步长——两个相邻值之间的差别 24 改变——用户修改值的字典 25 """ 26 self.start = start 27 self.step = step 28 self.changed = {} 29 30 31 def __getitem__(self, key): 32 """ 33 Get a item from the arithmic sequence. 34 """ 35 checkIndex(key) 36 37 try: 38 return self.changed[key] # 修改了吗? 39 except KeyError: # 否则…… 40 return self.start + key*self.step # ……计算值 41 42 43 def __setaitem__(self, key, value): 44 45 """ 46 修改算数序列中的一个项 47 """ 48 checkIndex(key) 49 50 self.changed[key] = value # 保存改后的值

 

posted @ 2018-05-26 22:04  kr1stoff  阅读(170)  评论(0编辑  收藏  举报