第一版Python程序

# -*- coding: cp936 -*-
import os
import cPickle as p

class Person:
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
    def __str__(self):
        return "Name:"+self.name+" ,Age:"+self.age+" ,Sex:"+self.sex
class AB:#AddressBook
    def __init__(self):
        pass
    def add(self,person):
        self.ab[person.name]=person
        print 'New Person Added!'
    def delete(self,name):
        try:
            del self.ab[name]
            print 'Deleted! %s' % name
        except:
            print 'Delete %s failed!' % name
    def find(self,name):
        
        print self.ab.get(name,"not find!")
    def show(self):
        for name,person in self.ab.items():
            print person.name+"  "+person.age+"  "+person.sex

global abook
a_book_dir="ab.data"

abook=AB()
abook.ab={}

print '''<------------------>\n
Author: Mason \n
Version: 1.0 \n
Date: 11/5/2011 \n
<------------------>'''

while True:
    print "<------------------>"
    print "a:add a person"
    print "d:del a person"
    print "l:list all person"
    print "f:find a person by name"
    print "<------------------>"
    cmd=raw_input("输入命令:")
    if cmd=='a':
        print "input like this: name age sex"
        s=raw_input("person info:")
        info=s.split(" ")
        print info
        person=Person(info[0],info[1],info[2])
        abook.add(person)
    elif cmd=='d':
        name=raw_input("input name:")
        abook.delete(name)
    elif cmd=='l':
        abook.show()
    elif cmd=='e':
        break
    elif cmd=='f':
        abook.find(raw_input("name:"))
f= open("a_book_dir",'w')
p.dump(abook.ab,f)
f.close()

print "Thanks 4 using AB!"

实现一个Python初学者应该练习的通讯录功能,a、d、l、f功能。最终退出程序的时候讲通讯录保存在a_book_dir文件中。

你可能感兴趣的:(python,cmd,delete,input,通讯)