假期刚结束,还没状态啃大部头,把Swaroop.C.H的《简明Python教程》看了一遍,然后老老实实把书中最后一章留的问题给实现了一下,作为我的第一个Python程序记录到这里,待日后回头批判
程序分两个模块: ui和repr,其中ui负责与用户交互,repr负责内部数据的处理
repr中首先建立Person类表示一个条目(即一个人的信息):
######################################################################
# The difine of class Person
class Person:
'''Represent of a person
include someone's name, phone number and mail
data: self.name, self.phone, self.mail'''
def __init__(self, name, phone="", mail=""):
'''the constructor of class Person
parameter name must be string'''
self.name = name
self.phone = phone
self.mail = mail
然后建立Wab类代表电话本
######################################################################
# The difine of class Wab
class Wab:
"""Representation of a WAB book
data: self.wab={name:Person}
method: self.add_Person(person)
self.del_Person(person)
self.write2File(fileName)
self.readFrom(fileName)"""
def __init__(self, *persons):
'''Construct self.wab according to the input data
input: some instance of class Person
Attention: parameter persons must be instance of class Person'''
self.wab = {}
for i in persons:
self.wab[i.name] = i
def add_Person(self, person):
'''add a new item in the wab book. '''
self.wab[person.name] = person
def del_Person(self, person):
'''delete the specified item in self.wab
and then return it'''
if self.wab.has_key(person.name):
return self.wab.pop(person.name)
def write2File(self, fileName):
'''write the whole wab book to a specified file
paramter fileName must be string'''
f = file(fileName, 'wb')
cPickle.dump(self.wab, f)
f.close()
def readFrom(self, fileName):
'''read the wab book from a file
paramter fileName must be string'''
f = file(fileName)
self.wab = cPickle.load(f)
f.close()
ui模块主要是一个while循环,以实现与用户的交互:
while True:
cmd = raw_input("Please enter a command:\
A(dd)/C(heck)/D(elete)/Q(uit)\n")
if cmd[0]=='a' or cmd[0]=='A':
name = raw_input("Please enter the name: ")
add_Rec(name)
elif cmd[0]=='c' or cmd[0]=='C':
name = raw_input("Please enter the name: ")
chk_Rec(name)
elif cmd[0]=='d' or cmd[0]=='D':
name = raw_input("Please enter the name: ")
del_Rec(name)
print name+"'s record has been removed!"
elif cmd[0]=='q' or cmd[0]=='Q':
quit = raw_input("Are you sure to quit?(y/n) ")
if quit[0] == 'y' or quit[0] == 'Y':
break
else:
pass
两个模块并不是同一天写的,ui模块中的add_Rec()函数等并没有重用repr.Wab类中的方法,其实那里头号多方法都没有必要。
最后,附上源代码
 |
文件: | myWAB.tar.gz |
大小: | 2KB |
下载: | 下载 |
|
阅读(620) | 评论(1) | 转发(0) |