反射的应用

class Teacher:
    OPERATE_DIC = [
        ('创建课程', 'create_course'),
        ('创造学生', 'create_student'),
        ('创建课程', 'create_course'),
        ('查看学生信息', 'check_student_info'),
    ]

    def __init__(self, name):
        self.name = name

    def create_course(self):
        print('创建课程')

    def create_student(self):
        print('创建学生')

    def check_student_info(self):
        print('查看学生信息')

    def check_all_student(self):
        print('查看所有学生')


class Student:
    OPERATE_DIC = [
        ('查看所有课程', '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('查看已选课程')


def longin():
    username = input('输入账号:')
    password = input('输入密码:')

    with open('userinfo.txt', 'r', encoding='utf-8') as f:
        for line in f:
            user, pwd, ident = line.split()
            if user == username and pwd == password:
                print('登录成功!')
                return username, ident


import sys


def main():
    usr, id = longin()
    print('user,id:', usr, id)
    file = sys.modules['__main__']
    cls = getattr(file, id)
    print(cls)
    obj = cls(usr)
    operate_dic = cls.OPERATE_DIC
    while 1:
        for num, i in enumerate(operate_dic, 1):
            print(num, i[0])

        choice = int(input('num>>>'))
        choice_item = operate_dic[choice - 1]
        getattr(obj, choice_item[1])()


main()

 

posted @ 2018-08-01 08:07  小学弟-  阅读(120)  评论(0编辑  收藏  举报