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")
  • 相关阅读:
    jQuery的简单函数
    Playwright-录制脚本进行自动化测试
    使用requests爬取图片并下载
    使用jmeter对websocket进行性能测试
    selenium定位动态元素的2种情况
    Python-Faker
    关于css中@media的基本使用方法
    selenium-浏览器窗口最大化、刷新、前进、后退
    selenium-滚动条滑动,iframe切换,切换窗口
    jmeter-阶梯式压测
  • 原文地址:https://www.cnblogs.com/xuwenwei/p/14409821.html
Copyright © 2011-2022 走看看