Python动态函数名称 [英] Python dynamic function names

查看:146
本文介绍了Python动态函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相对于使用if/else语句,我正在寻找一种更好的方法来基于Python中的变量来调用函数.每个状态码都有对应的功能

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

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

推荐答案

做到这一点的典型方法是使用字典来模拟switchif/elif.您将在SO上找到一些类似问题的问题.

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.

将您的函数放入以状态代码为键的字典中:

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)

这篇关于Python动态函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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