"""
Created on Tue May 22 23:10:37 2018
@author: biok
"""
def checkIndex(key):
"""
所给的键是能接受的索引吗?
为了能被接受,键应该是一个非负的整数。如果他不是整数,会引发TypeError;如他是负数
则会引起IndexError(因为序列是无限长的)。
"""
if not isinstance(key, int): raise TypeError
if key<0: raise IndexError
class ArithmeticSequence:
def __init__(self, start=0, step=1):
"""
初始化算数序列
起始值——序列中的第一个值
步长——两个相邻值之间的差别
改变——用户修改值的字典
"""
self.start = start
self.step = step
self.changed = {}
def __getitem__(self, key):
"""
Get a item from the arithmic sequence.
"""
checkIndex(key)
try:
return self.changed[key] # 修改了吗?
except KeyError: # 否则……
return self.start + key*self.step # ……计算值
def __setaitem__(self, key, value):
"""
修改算数序列中的一个项
"""
checkIndex(key)
self.changed[key] = value # 保存改后的值
python基础教程——9.3成员访问
猜你喜欢
转载自www.cnblogs.com/kristoff/p/9094508.html
今日推荐
周排行