程序的功能:创建一个的命令行 地址簿 程序。在这个程序中,可以添加、删除和搜索你的联系人(朋友、家人和同事等等)以及它们的信息(诸如电子邮件地址和/或电话号码)。
代码很少,如下:
import cPickle as cp
persons = {}
class Person(object):
name = 'unknown'
sex = 'unknown'
age = '0'
relation = 'unknown'
phone = 'unknown'
email = 'unknown'
def __init__(self,name):
self.name = name
def __str__(self):
return "name:%s sex:%s age:%s phone:%s email:%s" % (self.name,self.sex,self.age,self.phone,self.email)
def load():
f = file("addrs.data",'r')
if f.readline():
# file pointer untreads
f.seek(0,0)
persons = cp.load(f)
f.close()
return True
else:
f.close()
return False
def dump():
f = file("addrs.data",'w')
cp.dump(persons,f)
f.close()
def add(name):
if load():
print 'true'
if persons.has_key(name):
s = raw_input("This person exists, do you want to override the information?y or n:")
if s=='n' or s=='N':
return
p = Person(name)
p.sex = raw_input("sex:")
p.age = raw_input('age:')
p.relation = raw_input('relation:')
p.phone = raw_input('phone:')
p.email = raw_input('email:')
persons[name] = p
dump()
def delete(name):
if not load():
print 'no data'
return
#delete the person
if persons.has_key(name):
del persons[name]
print "%s has been deleted" % name
else:
print "no such person"
dump()
def search(name):
if not load():
print 'no data'
return
if persons.has_key(name):
print persons[name]
else:
print 'no such person'
程序很小,不过是我写的第一个完整的python程序,写下来纪念一下