python 通讯录课程设计_如何用Python设计一个通讯录类?

直接上代码:一共三个文件

CommunicateClass.py

# @File : CommunicateClass.py

class Communicate():

"""

设计一个通讯录类,包括:

姓名、电话号码、性别、年龄、工作单位

"""

def __init__(self, list):

self.__name = list[0]

self.__tel=list[1]

self.__sex=list[2]

self.__age=list[3]

self.__workspace=list[4]

def __str__(self):

return 'name: %s,tel: %s,sex: %s,age: %s,workspace: %s' % (self.__name, self.__tel,self.__sex,self.__age,self.__workspace)

@property

def name(self):

return self.__name

@property

def tel(self):

return self.__tel

@property

def sex(self):

return self.__sex

@property

def age(self):

return self.__age

@property

def workspace(self):

return self.__workspace

@name.setter

def name(self, name):

self.__name = name

@tel.setter

def tel(self, tel):

self.__tel = tel

@sex.setter

def sex(self, sex):

self.__sex = sex

@age.setter

def age(self, age):

self.__age = age

@workspace.setter

def workspace(self, workspace):

self.__workspace = workspace

CommunicateImpl.py

# @File : CommunicateImpl.py

from CommunicateClass import *

from xpinyin import Pinyin

class comImpl():

"""

1.统计有多少个男性和女性的人数

2.按姓名对通讯录排序,显示排序后的通论录信息

3.求所有人的平均年龄。

"""

def getNumber(scan):

man = 0

woman = 0

for i in range(0, len(scan)):

if scan[i].sex == "男" or scan[i].sex == "man":

man += 1

elif scan[i].sex == "女" or scan[i].sex == "woman":

woman += 1

print("男生:" + str(man) + "人", "女生" + str(woman) + "人")

def getInfoOrderbyname(scan):

"scan 是list"

# p1 = sorted(scan, key=lambda s: s.name)

# for p in p1:

# print(p)

# 输入一个名字的列表

pin = Pinyin()

result=[]

for i in range(len(scan)):

# for item in scan[i].name:

result.append((pin.get_pinyin(scan[i].name), scan[i]))

result.sort()

print(result)

for i in range(len(result)):

result[i] = result[i][1]

for p in result:

print(p)

def getAverage(scan):

# 先计算键盘输入了多少条记录

allage = 0

total = len(scan)

for i in range(total):

allage += int(scan[i].age)

print("所有人的平均年龄为:" + str(allage / total))

testComm.py

# @File : testComm.py

from CommunicateClass import Communicate

from CommunicateImpl import comImpl

class test():

"从键盘输入n个人的通讯录信息"

def getInput(self):

# 范围自由指定吧 或者改成while 循环

lis1=[]

for i in range(0,2):

li = input("请输入姓名、电话号码、性别、年龄、工作单位,以逗号隔开:")

strList = li.split(" ")

print(strList)

if len(strList) != 5:

print("请输入5列:")

continue

else:

#构造Communicate 对象

lis1.append(Communicate(strList))

# print(lis1)

print("----我是分割线----")

comImpl.getNumber(lis1)

print("----排序后的----")

comImpl.getInfoOrderbyname(lis1)

comImpl.getAverage(lis1)

a=test()

a.getInput()

说明:

1.一共三个文件 同一文件夹下

2.从键盘输入n个人的通讯录信息,testComm.py文件中设置的是2,可将其修改为想要的数字

3.from xpinyin import Pinyin 如果报错的话 ,先pip install xpinyin

以上,希望对你有所帮助。

你可能感兴趣的:(python,通讯录课程设计)