python练习题---实现一个通讯录

#!/usr/bin/python3
#-*-encoding:utf-8-*-
"""
@project_name = pytest
@file = TongXunLu.py
@author = angel
@create_time = 2018/9/23 18:44
"""

'''
创建一个类似于通讯录功能的类,要求如下
1.通讯录要有名字,如'xxx的通讯录'
2.类能实现一般的通讯功能,例如:
  联系方式录入,修改,删除,精确查找,匹配姓名,显示目前有多少联系人。(暂时假定一个人只有一个联系方式)
3.类有模拟拨号功能
4.类支持通讯录导出功能,能把当前的通信录导出到指定文件
'''
#-------------------------定义通讯录类-----------------------------------------
class tongxunlu:
    def __init__(self,name):
        self.__name=name
        self.__book=dict()
    def showTname(self):
        print("%s的通讯录"% self.__name)
    def show_book(self):
        print(self.__book)
    def load(self,name,number):
        self.__book[name]=number
    def change_number(self,name,newnumber):
        self.__book[name]=newnumber
    def change_name(self,name,newname):
        number=self.__book[name]
        self.__book.pop(name)
        self.__book[newname] = number
    def del_name(self,name):
        self.__book.pop(name)
    def match(self,name):
        match_name = [i for i in self.__book.keys() if name in i]
        if len(match_name)==0:
            print("no one name contains %s"% name)
        else:
            for i in match_name:
                print("%s : %s"% (i,self.__book[i]))
    def show_member(self):
        return len(self.__book)
    def calling(self,number):
        print("now is calling %d" % number)
    def write_out(self,path):
        with open(path, 'w') as f:
            for i in self.__book.keys():
                f.write(i+":"+str(self.__book[i])+'\n')
# ----------------------测试--------------------------------------------------
# 设置通讯录名字
t1 = tongxunlu("hxb")
t1.showTname()
# 向通讯录添加记录
t1.load("张三",346542364)
t1.load('李四',464167649)
t1.load('王五',764846411)
t1.show_book()
# 修改记录 的key
t1.change_name("张三","张十三")
t1.show_book()
# 修改记录 的value
t1.change_number('张十三', 164458317)
t1.show_book()
# 按关键字查询
t1.match("张")
t1.match('赵')
# 查询总共有多少条记录
print(t1.show_member())
# 拨打电话
t1.calling(164458317)
# 导出通讯录到某个文件中
t1.write_out('./txl.txt')

python练习题---实现一个通讯录_第1张图片

你可能感兴趣的:(Python3,python从入门到精通)