最近学习Python,看了入门书《A Byte Of Python》,这本书很薄,例子很多,非常适合自学。虽然不能深入理解,但是对于我这种随便用用的已经足够了。在最后,作者出了一个问题,让大家写一个地址簿。我简单的实现了一个,发现真的不难。
当然能写出这么“大”的程序,也归功于我之前一直按照书里的代码写了许多小程序。
#! /usr/bin/python
#Filename: address-book.py
#Author: gogdizzy
import sys
import os
import pickle
class PersonInfo:
def __init__( self, name, age, tel, email ):
self.name = name
self.age = age
self.tel = tel
self.email = email
def display( self ):
print 'Name: {0}\nAge: {1}\nTel: {2}\nEmail: {3}'.format( self.name, self.age, self.tel, self.email )
class AddrBook:
def __init__( self ):
self.dict = {}
def put( self, name, info ):
self.dict[name] = info
def get( self, name ):
if( self.dict.has_key( name ) ):
self.dict[name].display()
else:
print name, 'is not in address book'
if ( len( sys.argv ) != 2 ):
sys.exit( 'Usage: {0} datafile'.format( sys.argv[0] ) )
db_file = sys.argv[1]
ab = AddrBook()
if ( os.path.isfile( db_file ) ):
print 'Load data from', db_file
fd = open( db_file, "rb" )
try:
ab = pickle.load( fd )
except:
sys.exit( 'File format error' )
finally:
print 'close', db_file
fd.close()
else:
print db_file, 'is not exist, create it'
fd = open( db_file, 'wb' )
try:
while True:
cmd = raw_input( '\nPlease input cmd( \'p\'ut \'g\'et \'q\'uit ): ' )
if ( cmd == 'g' ):
ab.get( raw_input( '\nplease input name: ' ) )
elif( cmd == 'p' ):
while True:
name = raw_input( '\nplease input name: ' )
if( len(name) > 0 ):
break
while True:
try:
age = int( input( '\nplease input age(integer): ' ) )
if( age < 0 ):
raise Exception()
except:
print 'Please input a positive integer'
continue
else:
break
tel = raw_input( '\nplease input tel: ' )
email = raw_input( '\nplease input email: ' )
ab.put( name, PersonInfo(name, age, tel, email) )
elif( cmd == 'q' ):
break
finally:
pickle.dump( ab, fd )
fd.close()