zoukankan      html  css  js  c++  java
  • 反射应用(能简化代码,更加优美)

    import sys
    
    def login():
        username = input("user:")
        password = input("pwd:")
        with open("userinfo","r",encoding="utf-8") as f:
            for line in f:
                user,pwd,ident = line.strip("
    ").split("|")
                if user == username and pwd == password:
                    print("登录成功")
                    return user,ident
    
    class Manager:
        OPERATE_LIST = [
            ("创建学生账号", "create_student"),
            ('创建课程', 'create_course'),
            ('查看学生信息', 'check_student_info')
        ]
        def __init__(self,name):
            self.name = name
    
        def create_student(self):
            print('创建学生账号')
        def create_course(self):
            print('创建课程')
        def check_student_info(self):
            print('查看学生信息')
    
    class Student:
        OPERATE_LIST = [
            ("查看课程", "check_course"),
            ('选课', 'choose_course'),
            ('查看已选择的课程', 'choosed_course')
        ]
        def __init__(self, name):
            self.name = name
    
    
        def check_course(self):
            print('查看课程')
    
    
        def choose_course(self):
            print('选课')
    
    
        def choosed_course(self):
            print('查看已选择的课程')
    
    class Teacher:
        OPERATE_LIST = [
            ("查看已有学生", "check_student"),
            ('查看已有学生', 'check_student'),
            ('查看学生信息', 'check_info')
        ]
        def __init__(self, name):
            self.name = name
    
        def check_student(self):
            print("查看已有学生")
    
        def check_student(self):
            print('查看已有学生')
    
        def check_info(self):
            print('查看学生信息')
    
    def main():
        user,id = login()
        print(user,id)
        file = sys.modules["__main__"]
        # print(file)
        cls = getattr(file,id)
        obj = cls(user)
        operatr_list = cls.OPERATE_LIST
        while True:
            for i in enumerate(operatr_list,1):
                print(i)
            num = input("选择:")
            if num.isdigit():
                num = int(num) - 1
                choose = operatr_list[num][1]
                # print(choose)
                getattr(obj, choose)()
            elif num.upper() == "Q":
                break
    
            else:
                print("重新输入")
    
    
    main()

    userinfo:

    abc|123|Manager
    ly|123|Student
    yan|123|Teacher
  • 相关阅读:
    剑指Offer(书):重建二叉树
    剑指Offer(书):从尾到头打印链表
    剑指Offer(书):替换空格
    剑指Offer(书):二维数组中的查找
    剑指Offer(书):数组中重复的数字
    剑指Offer(书):实现单例模式
    Centos 7安装Mysql5.7
    3000客接口迁移一记
    安装完Centos 7后的一些处理
    算法笔记—入门篇(2)—算法初步(更新中......)
  • 原文地址:https://www.cnblogs.com/yfjly/p/10598616.html
Copyright © 2011-2022 走看看