从关键字参数中省略long“if,elif,elif,else”

2024-09-24 02:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在类方法中,我为一个关键字参数提供了一组可能的选项,每个选项都有一个不同的算法来计算某些东西。为了检查哪个选项被添加到关键字中,我做了一个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语句的列表?在


Tags: 方法算法列表参数ifmy选项myclass
3条回答

使用字典:

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
}

其他地方:

^{pr2}$

总有至少一个地方需要你来划分案件。

在您的例子中,您设置了一个字符串,然后再次进行比较。在

一种“方法”是直接用不同的函数/方法调用代替设置字符串,而不是在函数中路由字符串。或者使用字典将字符串映射到函数调用。在

用字典是个好主意。但是,另一个选项是反射,它是由字符串调用的函数。在

class MyClass:
    def handle_spacial(self):
        print('Cool stuf')

    def handle_discoidal(self):
        print('OTHER cool stuff')

    def handle_temporal(self):
        print('You get the gist')

    def default(self):
        print('not in options list')

    def my_method(self, my_parameter, my_keyword='spacial'):
        function_name = "handle_"+my_keyword
        if hasattr(self, function_name):
            getattr(self, function_name)()
        else:
            self.default()

相关问题 更多 >