zoukankan      html  css  js  c++  java
  • 由“反射”,联想到的动态调用不同模块的函数

    # !/usr/bin/env python
    # -*- coding:utf8 -*-
    
    # from lib import account
    
    # url = input("请模拟输入 url 页面: ")
    #
    # if url.endswith("login"):
    #     r = account.login()
    #     print(r)
    #
    # elif url.endswith("logout"):
    #     r = account.logout()
    #     print(r)
    #
    # elif url.endswith("nb"):
    #     r = account.nb()
    #     print(r)
    #
    # else:
    #     print("404")
    
    
    # 当account中含有很多的函数体时,当前的主程序 index.py ,就要写很多的elif 条件来判断。
    # 而通过“反射”, 根据用户的输入是什么,再去account中调用相应的函数才比较合适
    
    # from lib import account
    #
    # input_info = input("请模拟输入相应的url: ")
    #
    # url = input_info.split("/")[-1]
    # if hasattr(account, url):
    #     target_func = getattr(account, url)
    #     r = target_func()
    #     print(r)
    #
    # else:
    #     print("404")
    
    
    """
    上述一个不好的地方是,所有的函数需要都写到单一的模块account中,
    但是通常情况下,每个函数是有分类的。
    不同种类的模块,包含不同的函数
    """
    
    '''
    对上述主程序继续优化
    要求用户输入: 模块名/函数名(account/login)
    '''
    
    modul_url = input("请输入url:(模块名/函数名)")
    
    target_module, target_func = modul_url.split("/")
    
    # 获取导入的模块
    module = __import__("lib." + target_module, fromlist=True)
    
    if hasattr(module, target_func):
        result = getattr(module, target_func)
        ret = result()
        print(ret)
    
    else:
        print("404")
  • 相关阅读:
    济南学习 Day5 T3 晚
    Codevs 1043 ==洛谷 P1004 方格取数
    济南学习 Day 5 T2 晚
    济南学习 Day 5 T1 晚
    济南学习 Day 5 T3 am
    济南学习 Day 5 T2 am
    LeetCode Weekly Contest 8
    poj-1410 Intersection
    leetcode-Warm Up Contest-Aug.21
    poj-1384 Piggy-Bank
  • 原文地址:https://www.cnblogs.com/xuwenwei/p/14409821.html
Copyright © 2011-2022 走看看