Python 初学笔记:地址簿练习

《简明Python教程》(点击打开链接)里有一个关于地址簿练习的提议,个人觉得很有意思,刚好也练练手。具体实现代码如下:

# Filename: adsbook.py

import cPickle
import os

class Person:
    fname = "adsbook.pd"
    adslist = {}
    def __init__(self, name, age, email, phone):
        self.name = name
        self.age = age
        self.email = email
        self.phone = phone
        Person.adslist[name] = [age, email, phone]
        # print "Name: %s; Age: %s;\nEmail: %s;\nPhone: %s;\n\twas created." \
        #      % (name, age, email, phone)
    def __del__(self):
        # print "%s has been deleted." % self.name
        pass
    
        
class NameIsNullError(IOError):
    def __init__(self, errstr):
        IOError.__init__(self)
        self.errstr = errstr
        print errstr

def Validate(input_str):
    if len(input_str) == 0:
        return 'Unknow'
    else:
        return input_str

def Save(adslist, fname):
    if len(adslist) >= 1:
        f = file(fname, 'w')
        cPickle.dump(adslist, f)
        f.close()
    else:
        pass

if os.path.isfile(Person.fname):
    f = file(Person.fname)
    Person.adslist = cPickle.load(f)
    f.close()
else:
    pass


flag = True

while flag:
    s = raw_input("Enter your option --->")
    if s == 'quit':
        flag = False
    elif s == 'help':
        print '''help: help!!!;
quit: quit;
version: version;
add: add a new person;
modify: modify some info.;
del: delete one's info.;
find: find details about s.b.;
save: save the info..
'''
    elif s == 'version':
        print 'Version 1.0.0'
    elif s == 'add' or s == 'modify':
        name = raw_input("Name: --->")
        if len(name) == 0:
            raise NameIsNullError('Error: input name is null')
        elif Person.adslist.has_key(name) and s == 'add':
            print 'A person called %s has already exists.\
            Do you want to update his/her information? (y/n)' % name
            if raw_input() == 'n':
                continue
            else:
                pass
        age = raw_input("Age: --->")
        # age = Validate(age)
        email = raw_input("Email: --->")
        # email = Validate(email)
        phone = raw_input("Phone: --->")
        # phone = Validate(phone)
        Person(name, age, email, phone)
    elif s == 'del':
        name = raw_input("Enter the name to be deleted: --->")
        if len(name) == 0:
            pass
        elif Person.adslist.has_key(name):
            del Person.adslist[name]
            print '%s has been deleted.' % name
        else:
            print 'The name you entered does not exists.'
    elif s == 'find':
        name = raw_input("Enter the name you want to find out: --->")
        if len(name) == 0:
            pass
        elif not Person.adslist.has_key(name):
            print r"The name you entered doesn't exists."
        else:
            print "Name: %s; Age: %s;\nEmail: %s;\nPhone: %s;"\
                  % (name, Person.adslist[name][0], Person.adslist[name][1], \
                     Person.adslist[name][2])
    elif s == 'save':
        Save(Person.adslist, Person.fname)
        print 'Done'
    else:
        print 'Unknow option.'
            
# Save to pickler
Save(Person.adslist, Person.fname)

代码运行起来,暂时感觉效果还可以,以后有机会再做改进。


附:Python类,当创建的新对象与原有对象同名时,会自动删掉原来的对象。或者说当一个对象没有引用时,它就会被立即删掉。例如下面一段程序,对变量p二次赋值时,原有的对象Sinjon就自动调用__del__方法删掉了。

class Person:
    population = 0
    def __init__(self, name, age):
        self.name = name
        self.age = age
        Person.population += 1
        print 'initializing person:\n Name %s Age %s' % (name, age)
    def __del__(self):
        Person.population -= 1
        print 'deleting person:\n name %s' % self.name
    def sayHello(self):
        print 'Hello, my name is', self.name
    def howMany(self):
        if Person.population == 1:
            print 'I am the only person here.'
        else:
            print 'We have %d persons here.' % Person.population

p = Person('Sinjon', 25)
p.sayHello()
p.howMany()
p = Person('Candy', 25)
p.sayHello()
p.howMany()

输出:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值