标签:习题 常量 out 打印 learn %s splay range pen
1.编写程序, 编写一个学生类, 要求有一个计数器的属性, 统计总共实例化了多少个学生
class Student: """学生类""" count = 0 # 计数 def __init__(self, name, age): self.name = name self.age = age Student.count += 1 # 要使得变量全局有效,就定义为类的属性 def learn(self): print("is learning") stu1 = Student("jack", 33) stu2 = Student("amy", 24) stu3 = Student("lucy", 22) stu4 = Student("lulu", 45) print("实例化了%s个学生" % Student.count) 输出: 实例化了4个学生
2.编写程序, A 继承了 B, 俩个类都实现了 handle 方法, 在 A 中的 handle 方法中调用 B 的 handle 方法
class B: """类B""" def __init__(self): pass def handle(self): print("B.handle") class A(B): """类A""" def __init__(self): super().__init__() def handle(self): super().handle() # super依赖于继承 a = A() a.handle() 输出: B.handle
3.编写程序, 如下有三点要求:
用户数据结构:user_info
{ "egon":{"password":"123",‘status‘:False,‘timeout‘:0}, "alex":{"password":"456",‘status‘:False,‘timeout‘:0}, }
import json import time # data = { # "egon":{"password":"123",‘status‘:False,‘timeout‘:0}, # "alex":{"password":"456",‘status‘:False,‘timeout‘:0}, # } # # with open("user_info", "w", encoding="utf-8") as f: # json.dump(data, f) # 序列化 class User: """用户类""" def __init__(self): self.user_dic = self.read() # 初始化时将用户信息读取出来 self.username = "" # 记录当前登录用户 def write(self): """序列化""" with open("user_info", "w", encoding="utf-8") as f: json.dump(self.user_dic, f) # 序列化 def read(self): """拿到用户数据""" with open("user_info", "r", encoding="utf-8") as f: user_dic = json.load(f) # 反序列化 return user_dic def db(self): print("用户数据结构:", self.user_dic) def login(self): """登录""" i = 0 while i < 3: username = input("username:").strip() password = input("password:").strip() if username in self.user_dic and password == self.user_dic[username]["password"]: time_now = time.time() # 获取当前时间 period = time_now - self.user_dic[username]["timeout"] # 时间差 if period >= 30: # 判断时间间隔是否满足登录条件 print("------%s登陆成功-----" % username) self.username = username self.user_dic[username]["status"] = True # 记录用户登录状态 self.write() # 将修改保存到文件 break else: print("用户处于锁定状态,请%s S后再试" % (30 - period)) break else: print("用户名或密码错误!") i += 1 if i == 3 and username in self.user_dic: self.user_dic[username]["timeout"] = time.time() # 记录3次登录失败的时间点 self.write() # 将修改保存到文件 exit("退出") def exit(self): """退出""" if self.username: # 用户处于登录状态 self.user_dic[self.username]["status"] = False # 修改用户登录状态 self.write() # 将修改保存到文件 exit("用户%s退出登录" % self.username) def help_info(self): """帮助信息""" print("""命令列表: 查看数据结构:db 登录:login 退出登录:exit""") def handle(self): """处理用户输入命令""" while True: cmd = input("请输入命令:").strip() cmd = cmd.split() if hasattr(self, cmd[0]): # 使用反射 func = getattr(self, cmd[0]) # 拿到方法名 func() else: self.help_info() # 打印帮助信息 user = User() if __name__ == "__main__": user.handle() """ 输出: 请输入命令:login username:egon password:123 ------egon登陆成功----- 请输入命令:exit 用户egon退出登录 """
4.用面向对象的形式编写一个老师角色, 并实现以下功能, 获取老师列表, 创建老师、删除老师、创建成功之后通过 pickle 序列化保存到文件里,并在下一次重启程序时能
读取到创建的老师, 例如程序目录结构如下.
proj |-- bin/ | |-- start.py 程序启动文件 |-- config/ | |-- settings.py 程序配置(例如: 配置存储创建老师的路径相关等) |-- db 数据存储(持久化, 使得每次再重启程序时, 相关数据对应保留) | |-- teachers/ 存储所有老师的文件 | |-- ... ... |-- src/ 程序主体模块存放 | |-- __init__.py | |-- teacher.py 例如: 实现老师相关功能的文件 | |-- group.py 例如: 实现班级相关的功能的文件 |-- main.py 程序运行主体程序(可进行菜单选择等) |-- README.md 程序说明文件
代码:
# start.py """程序启动文件""" import os import sys BASE_PATH = os.path.dirname(os.getcwd()) sys.path.insert(0, BASE_PATH) # 将proj的路径添加到模块搜索路径中 from src import main if __name__ == "__main__": main.main() # settings.py """定义一些常量""" import os BASE_PATH = os.path.dirname(os.getcwd()) teacher_file = os.path.join(BASE_PATH, "db", "teacher_info") # 教师文件路径 # main.py """程序运行主体,可进行菜单选择""" from src.manager import Manager def main(): li = Manager.info for i in range(len(li)): print(i+1, li[i][0]) while True: ch = input("输入序号进行操作:").strip() getattr(Manager(), li[int(ch)-1][1])() # 反射, 找到对象相应的方法并执行 # manager.py """创建教师,删除教师,查看教师""" from src.my_pickle import MyPickle from config.settings import * from src.teacher import Teacher class Manager: """管理员类""" info = [("查看教师", "show_teacher"),("创建教师", "create_teacher"), ("删除教师", "delete_teacher"), ("退出", "exit")] def __init__(self): self.teacher_pickle_obj = MyPickle(teacher_file) # 实例化MyPickle类,teacher_file是settings中的教师文件路径 def show(self, pickle_obj): """从文件中读取信息""" pick_obj = getattr(self, pickle_obj) data_g = pick_obj.readiter() # 读取对象信息 for teacher_obj in data_g: for key in teacher_obj.__dict__: print(key, teacher_obj.__dict__[key]) # 打印对象信息 print("-" * 50) def show_teacher(self): """查看教师信息""" print("教师信息".center(45, "-")) self.show("teacher_pickle_obj") def create_teacher(self): """创建教师信息""" name = input("输入要创建的教师姓名:").strip() school = input("输入教师所在学校:").strip() teacher = Teacher(name, school) # 实例化一个教师对象 self.teacher_pickle_obj.write(teacher) # 将对象写入文件 print("创建教师成功!") def delete_teacher(self): """删除教师信息""" self.show_teacher() inp = input("输入要删除的教师姓名:").strip() self.teacher_pickle_obj.delete(inp) # 删除 print("删除成功!") def exit(self): exit() # my_pickle.py """读写文件信息""" import pickle import os from config.settings import * class MyPickle: def __init__(self, filename): self.filename = filename def write(self, data): # 写入 with open(self.filename, "ab") as f: pickle.dump(data, f) def readiter(self): # 读取 with open(self.filename, "rb") as f: while True: try: data = pickle.load(f) yield data except: break def delete(self, name): # 删除 f2 = MyPickle(self.filename+".bak") # 新建一个文件 for item in self.readiter(): # 从文件中load数据 if item.name == name: pass # 找到了就不写入 else: f2.write(item) # 没找到就将对象写入文件 os.remove(self.filename) # 删除旧文件 os.rename(self.filename+".bak", self.filename) # 新文件名重命名为旧文件名 # teacher.py class Teacher: """教师类""" def __init__(self, name, school): self.name = name self.school = school
标签:习题 常量 out 打印 learn %s splay range pen
原文地址:https://www.cnblogs.com/yanlin-10/p/9123809.html