zoukankan      html  css  js  c++  java
  • python把字符串转换成函数或者方法

    先看一个例子:

    def foo():
        print("foo1")
    
    def bar():
        print("bar2")
    
    func_list = ["foo" ,"bar"]
    
    for func in func_list:
        func()

    >>>

    Traceback (most recent call last):
    File "D:/data/AutoTest_code/ML/test.py", line 21, in <module>
    func()
    TypeError: 'str' object is not callable

    
    

    我们希望遍历执行列表中的函数,但是从列表中获得的函数名是字符串,所以会提示类型错误,字符串对象是不可以调用的。如果我们想要字符串变成可调用的对象呢?或是想通过变量调用模块的属性和类的属性呢?以下有三种方法可以实现。

    eval()

    func_list = ["foo" ,"bar"]
    
    for func in func_list:
      
    locals()[func]()
    >>> foo1 bar2

    eval() 通常用来执行一个字符串表达式,并返回表达式的值。在这里它将字符串转换成对应的函数。eval() 功能强大但是比较危险(eval is evil),不建议使用。

    locals()

    func_list = ["foo" ,"bar"]
    
    for func in func_list:
      
    locals()[func]()
    
    
    >>>
    foo1
    bar2

    globals()

    func_list = ["foo" ,"bar"]
    
    for func in func_list:
      
    globals()[func]()
    >>> 
    foo1
    bar2

    locals() 和 globals() 是python的两个内置函数,通过它们可以一字典的方式访问局部和全局变量。

    Airtest自动化测试交流群:739857090
  • 相关阅读:
    Postman安装与使用
    最新的爬虫工具requests-html
    从高级测试到测试开发
    uiautomator2 使用Python测试 Android应用
    zalenium 应用
    Docker Selenium
    Java 测试驱动开发--“井字游戏” 游戏实战
    DevOps/TestOps概念
    Android测试(四):Instrumented 单元测试
    appium对博客园APP进行自动化测试
  • 原文地址:https://www.cnblogs.com/wutaotaosin/p/15392796.html
Copyright © 2011-2022 走看看