● 共两个文件:userInfo,reflex.py
alex|123456|Manager hezewei|666|Student taibai|2222|Teachar
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/27 11:26 # @Author : zejin # @File : reflex.py # 关于反射 class Manager: OPERATE_DIC = [ ("创建学生账号", "create_student"), ("创建课程", "create_course"), ("查看学生信息", "check_student") ] def __init__(self, name): self.name = name def create_student(self): print("创建学生账号") def create_course(self): print("创建课程") def check_student(self): print("查看学生信息") class Teachar: OPERATE_DIC = [ ("查看学生信息", "check_student"), ("给学生评分", "grage") ] def __init__(self, name): self.name = name def check_student(self): print("查看学生信息") def grage(self): print("给学生评分") class Student: OPERATE_DIC = [ ("查看课程", "check_course"), ("选择课程", "choose_course"), ("查看已选择的课程", "chooosed_course") ] def __init__(self, name): self.name = name def check_course(self): print("查看课程") def choose_course(self): print("选择课程") def chooosed_course(self): print("查看已选择的课程") def login(): username = input("user:") password = input("pwd:") with open('userInfo') as f: for line in f: user, pwd, ident = line.strip().split("|") if username == user and password == pwd: print("登录成功!") return username, ident else: return -1 import sys def main(): re = login() while re == -1: print("错误") re = login() user, id = re file = sys.modules["__main__"] # 得到本页面 cls = getattr(file, id) # 得到本页面的某个类,例:class Manager obj = cls(user) # 实例化此类的对象 opeate_dic = cls.OPERATE_DIC # 得到类中静态字段OPERATE_DIC while True: for num, i in enumerate(opeate_dic, 1): print(num, i[0]) choice = int(input("\n请输入数字选择(输入-1结束)>>>")) if choice == -1: break choice_item = opeate_dic[choice - 1] getattr(obj, choice_item[1])() # choice_item[1])为对象中方法名 main()