有什么方法可以从python3的字符串中定义函数名吗?

发布时间:2020-07-07 01:32

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

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

def test_first():
    test_code

def test_second():
    test_code

def test_third():
    test_code

...

测试代码都是相同的,所以我认为如果可以使用for循环这样的方法来定义pytest函数,它将变得更加简单

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

在python3中有可能吗?如果是这样,请您让我知道我该怎么做?

回答1

这是@ user2357112所提到的定义测试的一种奇怪方法,但我想您可以执行以下操作:

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()
回答2

不确定为什么要这样做,但是可以使用面向对象的Python来实现。

首先,定义一个类。

class Test:
    pass

定义您的功能。

def func1(self):
    print('I am func1.')

def func2(self):
    print('I am func2.')

def func3(self):
    print('I am func3.')

然后,将函数注入到类中。

testcases = ['first', 'second', 'third']
functions = [func1, func2, func3]

for i, tc in enumerate(testcases):
    setattr(Test, tc, functions[i])

然后,您可以将函数与字符串列表中的名称一起使用。

test = Test()

test.first()

# Output:
# I am func1.

test.second()

# Output:
# I am func2.

test.third()

# Output:
# I am func3.
回答3
testfiles = ['first.py', 'second.py', 'third.py']
test_code = 'print(\'hello\')'
def test_first():
    eval(test_code)


def test_second():
    eval(test_code)

def test_third():
    eval(test_code)

for filename in testfiles :
    func_name = 'def test_'+filename[:-3]+'():eval(test_code)'
    exec(func_name)
    eval('test_'+filename[:-3]+'()')