gpt4 book ai didi

python - 从关键字参数中省略长 'if, elif, elif, else'

转载 作者:行者123 更新时间:2023-12-01 04:56:22 25 4
gpt4 key购买 nike

在类方法中,我有一组针对单个关键字参数的可能选项,每个选项都有不同的算法来计算某些内容。为了检查哪个选项已添加到关键字中,我创建了一系列 if、elif、else 也找到了提供的关键字选项。

class MyClass:
def my_method(self, my_parameter, my_keyword='spacial'):
if my_keyword == 'spacial':
print('Cool stuf')
elif my_keyword == 'discoidal':
print('OTHER cool stuff')
elif my_keyword == 'temporal':
print('You get the gist')
else:
print('not in options list')

在我看来,这不是一种非常优雅的编码方式。特别是当选项列表不断增长时。有没有办法省略 if、elif、elif、else 语句列表?

最佳答案

使用字典:

def cool_stuff(param):
...

def other_cool_stuff(param):
...

def you_get_the_gist(param):
....


dispatch_mapping = {
'spacial': cool_stuff,
'discoidal': other_cool_stuff,
'temporal': you_get_the_gist
}

其他地方:

def my_method(self, param, keyword='spacial'):
handler = dispatch_mapping.get(keyword)
if handler is None:
raise Exception("No handler for %s" % keyword)
return handler(param)

关于python - 从关键字参数中省略长 'if, elif, elif, else',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27254562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com