在类方法中,我为一个关键字参数提供了一组可能的选项,每个选项都有一个不同的算法来计算某些东西。为了检查哪个选项被添加到关键字中,我做了一个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语句的列表?在
使用字典:
其他地方:
^{pr2}$总有至少一个地方需要你来划分案件。
在您的例子中,您设置了一个字符串,然后再次进行比较。在
一种“方法”是直接用不同的函数/方法调用代替设置字符串,而不是在函数中路由字符串。或者使用字典将字符串映射到函数调用。在
用字典是个好主意。但是,另一个选项是反射,它是由字符串调用的函数。在
相关问题 更多 >
编程相关推荐