Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这是一个;蟒蛇的;作为元组值的python开关语句执行函数的方法?_Python - Fatal编程技术网

这是一个;蟒蛇的;作为元组值的python开关语句执行函数的方法?

这是一个;蟒蛇的;作为元组值的python开关语句执行函数的方法?,python,Python,我有一种情况,我有六种可能的情况,可能与四种不同的结果有关。我不想使用扩展的if/else语句,而是想知道使用字典来调用我将在if/else中调用的函数来替代“switch”语句(如在C#或php中使用的)是否更符合Python 我的switch语句依赖于我用来构建元组的两个值,我将使用它们作为字典的键,该字典将用作我的“开关”。我将从另外两个函数(数据库调用)获取元组的值,这就是为什么我有示例one()和zero()函数 这是我在python shell中偶然发现的代码模式: def one(

我有一种情况,我有六种可能的情况,可能与四种不同的结果有关。我不想使用扩展的if/else语句,而是想知道使用字典来调用我将在if/else中调用的函数来替代“switch”语句(如在C#或php中使用的)是否更符合Python

我的switch语句依赖于我用来构建元组的两个值,我将使用它们作为字典的键,该字典将用作我的“开关”。我将从另外两个函数(数据库调用)获取元组的值,这就是为什么我有示例one()和zero()函数

这是我在python shell中偶然发现的代码模式:

def one():
    #Simulated database value
    return 1

def zero():
    return 0

def run():
    #Shows the correct function ran
    print "RUN"
    return 1

def walk():
    print "WALK"
    return 1

def main():
    switch_dictionary = {}

    #These are the values that I will want to use to decide
    #which functions to use
    switch_dictionary[(0,0)] = run
    switch_dictionary[(1,1)] = walk

    #These are the tuples that I will build from the database
    zero_tuple = (zero(), zero())
    one_tuple = (one(), one())

    #These actually run the functions. In practice I will simply 
    #have the one tuple which is dependent on the database information
    #to run the function that I defined before
    switch_dictionary[zero_tuple]()
    switch_dictionary[one_tuple]()
我没有编写实际的代码,或者我会将其发布在这里,因为我想知道这种方法是否被认为是python的最佳实践。我在大学里仍然是一名python学习者,如果这是一种坏习惯的方法,那么在我进入现实世界之前,我想现在就把它戒掉

注意,执行上述代码的结果与预期一样,只是“RUN”和“WALK”

编辑

对于那些感兴趣的人来说,这就是相关代码的结果。它正在谷歌应用程序引擎应用程序中使用。您应该发现代码比我的粗略示例模式整洁得多。它比我之前的复杂if/else树工作得更好

def GetAssignedAgent(self):
    tPaypal = PaypalOrder() #Parent class for this function
    tAgents = []
    Switch = {}

    #These are the different methods for the actions to take
    Switch[(0,0)] = tPaypal.AssignNoAgent
    Switch[(0,1)] = tPaypal.UseBackupAgents
    Switch[(0,2)] = tPaypal.UseBackupAgents
    Switch[(1,0)] = tPaypal.UseFullAgents
    Switch[(1,1)] = tPaypal.UseFullAndBackupAgents
    Switch[(1,2)] = tPaypal.UseFullAndBackupAgents
    Switch[(2,0)] = tPaypal.UseFullAgents
    Switch[(2,1)] = tPaypal.UseFullAgents
    Switch[(2,2)] = tPaypal.UseFullAgents

    #I'm only interested in the number up to 2, which is why
    #I can consider the Switch dictionary to be all options available.
    #The "state" is the current status of the customer agent system
    tCurrentState = (tPaypal.GetNumberofAvailableAgents(), 
                     tPaypal.GetNumberofBackupAgents())

    tAgents = Switch[tCurrentState]()

考虑一下这个成语:

>>> def run():
...   print 'run'
... 
>>> def walk():
...   print 'walk'
... 
>>> def talk():
...    print 'talk'
>>> switch={'run':run,'walk':walk,'talk':talk}
>>> switch['run']()
run
我认为这比你的方向更具可读性

编辑

这同样有效:

>>> switch={0:run,1:walk} 
>>> switch[0]()
run
>>> switch[max(0,1)]()
walk
您甚至可以将此习惯用法用于
开关/default
类型结构:

>>> default_value=1
>>> try:
...    switch[49]()
... except KeyError:
...    switch[default_value]()
或者(可读性较低,更简洁):

编辑2

同样的习语,延伸到你的评论:

>>> def get_t1():
...    return 0
... 
>>> def get_t2():
...    return 1
... 
>>> switch={(get_t1(),get_t2()):run}
>>> switch
{(0, 1): <function run at 0x100492d70>}
>>def get_t1():
...    返回0
... 
>>>def get_t2():
...    返回1
... 
>>>开关={(get_t1(),get_t2()):run}
>>>开关
{(0, 1): }

可读性很重要

根据字典或序列查找将函数分派给函数是一种相当常见的python实践

如果您使用索引进行查找,列表列表也可以:

switch_list = [[run, None], [None, walk]]
  ...
switch_list[zero_tuple]()

被认为最具python风格的是在满足其他操作要求的同时最大限度地提高清晰度。在您的示例中,查找元组似乎没有内在含义,因此操作意图是丢失一个神奇常量。尽量确保业务逻辑不会在调度机制中丢失。为常量使用有意义的名称可能会有所帮助。

问题是,我将根据数据库调用动态构造元组,因为我已经在根据函数中的数据库结果返回0、1或2。所以使用元组和单个字符串是非常必要的,因为我需要使用两个(将来可能会更多)值。我真的很喜欢使用“开关”作为字典的名称。但是,您可能希望考虑构建一个简单的类。总的来说,要记住可读性非常重要。像
switch\u dictionary[(0,0)]=run
zero\u tuple=(zero(),zero())
这样的东西对其他人(或几个月后的你自己)来说很难理解。Python倾向于非常可读。你选择的习语会有所不同。您可以以更可读的方式编写相同的代码。我的特定问题类似于客户服务系统,它将客户请求分配给两种不同类型的客户服务代理(我描述中的每一半元组),但它会根据每种在线代理的数量改变其行为。中的元组类似于(GetTier1(),GetTier2()),所以在这种情况下,元组可能是最可读的?我不习惯别人阅读我的python代码,所以我真的很感兴趣。您应该会发现该实现比我的第一个模式要好得多,可读性也更高。
switch[switch.get(49,默认值)]()
应该是
switch.get(49,switch.get(默认值))()
更好!可读性强且“Pythonic”注意,
Switch[(x,y)]
可以作为
Switch[x,y]
switch_list = [[run, None], [None, walk]]
  ...
switch_list[zero_tuple]()