在StudentEntity目录中定义函数
class Student:
def __init__(self,no,name,age,contact):
self.no=no
self.name=name
self.age=age
self.contact=contact
def __str__(self):
return "{},{},{},{}".format(self.no,self.name,self.age,self.contact)
if __name__=="__main__":
li=Student("2021","李四",20,123456)
print(li)
然后在DataAccess定义函数
from StudentEntity import Student
def loadStudents():
file=open("student.txt","r",encoding="utf-8")
lines=file.readlines()
students=[]
for line in lines:
a=line.split(",")
students.append(Student(a[0],a[1],int(a[3].strip('\n'))))
file.close()
return students
def saveStudents(students):
file=open("student.txt","w",encoding="utf-8")
for x in students:
file.write(str(x)+"\n")
file.close()
if __name__=="__main__":
a=loadStudents()
print(a)
a.append(Student("2024","赵六",21,20213011001))
print(a)
saveStudents(a)
最后,在main中,引用以上函数
import StudentEntity
from DataAccess import*
students=[]
def menu():
print('-' * 40)
print("欢迎使用学生通讯管理系统v2.0")
print("[1] 增加学员信息")
print("[2] 删除学员信息")
print("[3] 打印学员信息")
print("[4] 退出系统")
print('-' * 40)
def add(students):
no=input("请输入学员学号:")
name=input("请输入学员姓名:")
age=input("请输入学员年龄:")
contact=input("请输入学员联系方式:")
student=Student(no,name,age,contact)
students.append(student)
print("{}学员的信息已经成功添加!".format(student.name))
def remove(students):
no=input("请输入要删除的学员学号:")
for x in students:
if x.no==no:
print("学号为{}的{}同学被移除".format(x.no,x.name))
students.remove(x)
break
else:
print("没有找到该学员信息,请重试:")
if __name__=="__main__":
students=loadStudents()
while True:
menu()
op=int(input("请输入要进行的操作:"))
if op==1:
add(students)
elif op==2:
remove(students)
elif op==3:
for x in students:
print(x)
elif op==4:
print("感谢使用本系统,期待下次光临!")
break
else:
print("输入错误,请重新输入要操作的编号")
saveStudents(students)