python简明教程说的,写出这个就可以自称是python程序员了,哈哈
那个判断文件是不是空的方法没找到,写的不优雅
#Filename : addressbook.py
import cPickle as p
class AddressBook:
def __init__(self, filename):
self._filename=filename
f=file(self._filename)
if f.read:
self._person_list=p.load(f)
self._modified = False
f.close()
def _input_item(self,person_name):
phone_number=raw_input("Phone number:")
email=raw_input("Email address:")
self._person_list[person_name]=[phone_number,email]
def add(self):
person_name=raw_input("Name:")
if person_name in self._person_list:
print "%s has in the address book"%person_name
return None
self._input_item(person_name)
self._modified = True
def edit(self):
person_name = raw_input("Name:")
if not person_name in self._person_list:
print "%s has not in address book"%person_name
self._input_item(person_name)
self._modified = True
def find(self):
person_name=raw_input("Name to find:")
if person_name in self._person_list:
print person_name,self._person_list[person_name]
def delete(self):
person_name = raw_input("Name:")
if not person_name in self._person_list:
print "%s has not in address book"%person_name
return None
del self._person_list[person_name]
self._modified = True
def show_all(self):
for item in self._person_list:
print item,self._person_list[item]
def get_modified(self):
return self._modified
def save_all(self):
f=file(self._filename,'w')
p.dump(self._person_list,f)
f.close()
self._modified = False
_person_list ={}
class Person:
def add(self,info):
self.info = info
def print_usage():
print "option:"
print "a : add a person"
print "e : edit a person"
print "f : find a person"
print "d : delete a person"
print "l : list all people"
print "s : save the changed"
print "q : quit address book"
print_usage()
command = raw_input("enter your command #>")
address_book = AddressBook("data")
while command != "q":
if(command == "a"):
address_book.add()
elif(command =="e"):
address_book.edit()
elif(command =="f"):
address_book.find()
elif(command =="d"):
address_book.delete()
elif(command =="l"):
address_book.show_all()
elif(command == "s"):
address_book.save_all()
else:
print_usage()
command = raw_input("enter your command #>")
if address_book.get_modified():
c=raw_input("Not saved. Save all?(y/n)")
if(c=="y"):
address_book.save_all()
print "Good Bye!!"
阅读(858) | 评论(0) | 转发(0) |