且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从另一个函数名称计算一个函数名称

更新时间:2023-11-09 23:48:34

问题有两个部分.

最简单的部分是在每个字符串的前面加上'text _':

The easy part is just prefixing 'text_' onto each string:

tests = {test: 'test_'+test for test in myTestDict}

更难的部分实际上是按名称查找功能.这类事情通常不是一个好主意,但是您碰到了其中一种情况(生成测试)通常很有意义的情况.您可以通过在您模块的全局词典中查找它们来进行操作,例如这个:

The harder part is actually looking up the functions by name. That kind of thing is usually a bad idea, but you've hit on one of the cases (generating tests) where it often makes sense. You can do this by looking them up in your module's global dictionary, like this:

tests = {test: globals()['test_'+test] for test in myTestList}


如果测试存在于模块的全局范围之外的其他地方,则在相同的想法上会有不同之处.例如,使它们成为类的所有方法可能是一个好主意,在这种情况下,您可以这样做:


There are variations on the same idea if the tests live somewhere other than the module's global scope. For example, it might be a good idea to make them all methods of a class, in which case you'd do:

tester = TestClass()
tests = {test: getattr(tester, 'test_'+test) for test in myTestList}

(尽管代码很有可能位于 TestClass 内部,所以它将使用 self 而不是 tester .)

(Although more likely that code would be inside TestClass, so it would be using self rather than tester.)

当然,如果您实际上不需要该字典,则可以将理解更改为显式的 for 语句:

If you don't actually need the dict, of course, you can change the comprehension to an explicit for statement:

for test in myTestList:
    globals()['test_'+test]()


另一件事:在重新发明***之前,您是否已查看内置于其中的stdlib ,或在PyPI上可用?