Python游标重置函数 python重新定义运算符( 四 )


def edit_dvd(db):
old_title = find_dvd(db, "edit")
if old_title is None:
return
【Python游标重置函数 python重新定义运算符】title = Console.get.string("Title", "title", old_title)
if not title:
return
director, year, duration = db[old_title]
...
db[title]= (director, year, duration)
if title != old_title:
del db[old_title]
db.sync()
为对某个DVD进行编辑,用户必须首先选择要操作的DVD,也就是获取DVD 的标题 , 因为标题用作键,值则用于存放其他相关数据 。由于必要的功能在其他场合 (比如移除DVD)也需要使用,因此我们将其实现在一个单独的find_dvd()函数中,稍后将査看该函数 。如果找到了该DVD,我们就获取用户所做的改变 , 并使用现有值作为默认值,以便提高交互的速度 。(对于这一函数,我们忽略了大部分用户接口代码,因为其与添加DVD时几乎是相同的 。)最后,我们保存数据 , 就像添加时所做的一样 。如果标题未作改变 , 就重写相关联的值;如果标题已改变 , 就创建一个新的键-值对,并且需要删除原始项 。
def find_dvd(db, message):
message = "(Start of) title to " + message
while True:
matches =[]
start = Console.get_string(message, "title")
if not start:
return None
for title in db:
if title.lower().startswith(start.lower()):
matches.append(title)
if len(matches) == 0:
print("There are no dvds starting with", start)
continue
elif len(matches) == 1:
return matches[0]
elif len(matches)DISPLAY_LIMIT:
print("Too many dvds start with {0}; try entering more of the title".format(start)
continue
else:
matches = sorted(matches, key=str.lower)
for i, match in enumerate(matches):
print("{0}: {1}".format(i+1, match))
which = Console.get_integer("Number (or 0 to cancel)",
"number", minimum=1, maximum=len(matches))
return matches[which - 1] if which != 0 else None
为尽可能快而容易地发现某个DVD,我们需要用户只输入其标题的一个或头几个字符 。在具备了标题的起始字符后,我们在DBM中迭代并创建一个匹配列表 。如果只有一个匹配项 , 就返回该项;如果有几个匹配项(但少于DISPLAY_LIMIT, 一个在程序中其他地方设置的整数),就以大小写不敏感的顺序展示所有这些匹配项,并为每一项设置一个编号,以便用户可以只输入编号就可以选择某个标题 。(Console.get_integer()函数可以接受0,即便最小值大于0,以便0可以用作一个删除值 。通过使用参数allow_zero=False, 可以禁止这种行为 。我们不能使用Enter键,也就是说,没有什么意味着取消,因为什么也不输入意味着接受默认值 。)
def list_dvds(db):
start =”"
if len(db) DISPLAY.LIMIT:
start = Console.get_string(“List those starting with [Enter=all]”,"start”)
print()
for title in sorted(db, key=str.lower):
if not start or title.Iower().startswith(start.lower()):
director, year, duration = db[title]
print("{title} ({year}) {duration} minute{0}, by "
"{director}".format(Util.s(duration),**locals()))
列出所有DVD (或者那些标题以某个子字符串引导)就是对DBM的所有项进行迭代 。
Util.s()函数就是简单的s = lambda x: "" if x == 1 else "s",因此,如果时间长度不是1分钟,就返回"s" 。
def remove_dvd(db):
title = find_dvd(db, "remove")
if title is None:
return
ans = Console.get_bool("Remove {0}?".format(title), "no")
if ans:
del db[title]
db.sync()
要移除一个DVD,首先需要找到用户要移除的DVD,并请求确认 , 获取后从DBM中删除该项即可 。