有没有什么方法可以在python3中从字符串定义函数名? [英] Is there any method to define a function name from string in python3?

查看:39
本文介绍了有没有什么方法可以在python3中从字符串定义函数名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一些名为 'test_[strings]' 的函数用于 pytest,例如:

I want to define some functions named 'test_[strings]' to use for pytest, like :

testfiles = ['first.py', 'second.py', 'third.py', ... ]

def test_first():
    test_code

def test_second():
    test_code

def test_third():
    test_code

...

测试代码都是一样的,所以我想如果我能用for循环之类的东西来定义pytest函数会简单得多:

The test code is all same, so I think it'll be much simpler if I can define pytest functions by using something like for loop :

for filename in testfiles :
    func_name = 'test_'+filename.rstrip('.py')
    def func_name() :
        test_code

这在python3中可能吗?如果是,请您告诉我我该怎么做?

Is this possible in python3? And if it is, could you please kindly let me know how can I do that?

推荐答案

@user2357112 提到定义测试的方式很奇怪,但我想你可以这样做:

It's a bizarre way to define tests as mentioned by @user2357112, but I guess you can do something like this:

testcases = ['first', 'second', 'third']

def test_function():
  print("It worked")

for test in testcases:
  globals()["test_{}".format(test)] = test_function

test_first()
test_second()
test_third()

这篇关于有没有什么方法可以在python3中从字符串定义函数名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆