Python 动态函数名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/680941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python dynamic function names
提问by drjeep
I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function
我正在寻找一种更好的方法来调用基于 Python 中的变量的函数,而不是使用如下的 if/else 语句。每个状态码都有对应的功能
if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
return testfeed(*args, **kwargs)
...
I assume this will require some sort of factory function but unsure as to the syntax
我认为这将需要某种工厂函数,但不确定语法
回答by SilentGhost
回答by SilentGhost
The canonical way to do this is to use a dictionary to emulate switch
or if/elif
. You will find several questions to similar problems here on SO.
执行此操作的规范方法是使用字典来模拟switch
或if/elif
。您会在 SO 上找到几个类似问题的问题。
Put your functions into a dictionary with your status codes as keys:
将您的函数放入字典中,以您的状态代码为键:
funcs = {
'CONNECT': connect,
'RAWFEED': rawfeed,
'RAWCONFIG' : rawconfig,
'TESTFEED': testfeed
}
funcs[status](*args, **kwargs)
回答by vartec
assuming that these functions belong to some module:
假设这些函数属于某个模块:
import module
return getattr(module, status.lower()).__call__(*args, **kwargs)
回答by to-chomik
it seams that you can use getattr in a slightly different (in my opinion more elegant way)
它接缝您可以以稍微不同的方式使用 getattr(在我看来更优雅的方式)
import math
getattr(math, 'sin')(1)
or if function is imported like below
或者如果函数是像下面这样导入的
from math import sin
sin is now in namespace so you can call it by
sin 现在在命名空间中,因此您可以通过以下方式调用它
vars()['sin'](1)
回答by Eugene Morozov
Some improvement to SilentGhost's answer:
对 SilentGhost 答案的一些改进:
globals()[status.lower()](*args, **kwargs)
if you want to call the function defined in the current module.
如果要调用当前模块中定义的函数。
Though it looks ugly. I'd use the solution with dictionary.
虽然长得丑。我会使用带有字典的解决方案。
回答by hasen
Look at this: getattra as a function dispatcher
看看这个:getattra 作为函数调度器
回答by RailsSon
I encountered the same problem previously. Have a look at this question, I think its what you are looking for.
我以前遇到过同样的问题。看看这个问题,我认为它是你正在寻找的。
Hope this is helpful
希望这有帮助
Eef
埃夫
回答by linjunhalida
some change from previous one:
与上一个相比有一些变化:
funcs = {
'CONNECT': connect,
'RAWFEED': rawfeed,
'RAWCONFIG' : rawconfig,
'TESTFEED': testfeed
}
func = funcs.get('status')
if func:
func(*args, **kwargs)