1 #!/usr/bin/python
2 #coding=UTF-8
3 #FileName:address.py
4 #Python地址簿
5 importcPickle as p;6 importos;7 importsys;8 classAddress:9 '''Python地址簿'''
10 #构造函数
11 def __init__(self):12 self.dataFileName = 'address.data';13 self.dataPath = os.getcwd() +os.sep;14 handle = file(self.dataPath + self.dataFileName, 'w');15 try:16 self.peopleList =p.load(handle);17 except:18 print '%s is empty.initializing...'%(self.dataFileName);19 self.peopleList ={};20 handle.close();21 ###
22 #添加一个地址簿
23 #@access public
24 #@author zhaoyingnan 2016-03-01 10:10:46
25 #@param string username 人名
26 #@param string marks 备注
27 #@param string mobile 手机号码
28 #@param string email 邮箱
29 #@return mix
30 #@note
31 ###
32 defaddPeople(self, username, marks, mobile, email):33 '''添加一个地址簿'''
34 if self.peopleList.get(username, 404) == 404:35 newPeople = {'username':username, 'marks':marks, 'mobile':mobile, 'email':email};36 self.peopleList[username] =newPeople;37 else:38 'already exist.';39
40 ###
41 #删除一个地址簿
42 #@access public
43 #@author zhaoyingnan 2016-03-01 10:16
44 #@param string username 人名
45 #@return mix
46 #@note
47 ###
48 defdelPeople(self, username):49 if self.peopleList.get(username, 404) == 404:50 print '%s non-existent.'%(username);51 else:52 delself.peopleList[username];53 print 'ok.';54
55 ###
56 #修改一个地址簿
57 #@access public
58 #@author zhaoyingnan 2016-03-01 10:18
59 #@param string username 人名
60 #@param string index 索引(username/marks/mobile/email)
61 #@param string value 索引对应的值
62 #@return mix
63 #@note
64 ###
65 defupdatePeople(self, username, index, value):66 if self.peopleList.get(username, 404) == 404:67 print '%s non-existent.'%(username);68 #sys.exit('%s non-existent!'%(username));
69 else:70 self.peopleList[username][index] =value;71
72 ###
73 #获取列表
74 #@access public
75 #@author zhaoyingnan 2016-03-01 10:21
76 #@return string
77 #@note
78 ###
79 defgetPeople(self):80 if len(self.peopleList) >0:81 for username,arList inself.peopleList.items():82 print '-------------------------------';83 print '\t%s\t'%(username);84 for key,value inarList.items():85 print '%s\t%s'%(key, value);86 print '-------------------------------';87 else:88 print '%s is empty.'%(self.dataFileName);89
90 #将地址播存储在文件中
91 def __del__(self):92 handle = file(self.dataPath + self.dataFileName, 'w');93 p.dump(self.peopleList, handle);94 handle.close();95
96
97 address =Address();98 address.addPeople('lee', 'LiHongBin', 18911937250, '791520450@qq.com');99 address.addPeople('zhaoyn', 'ZhaoYingNan', 15932279586, '409586363@qq.com');100 address.addPeople('Mr.Zhu', 'ZhuXiaoHuan', 13303028786, '12802390939@qq.com');101 address.delPeople('Mr.Zhu');102 address.updatePeople('Liu', 'marks', 'LiuQing');103 address.updatePeople('zhaoyn', 'marks', 'Mr.Zhao');104 address.getPeople();