Pythonic way to have a choice of 2-3 options as an argument to a function

前端 未结 6 796
抹茶落季
抹茶落季 2021-02-07 07:16

I have a Python function which requires a number of parameters, one of which is the type of simulation to perform. For example, the options could be \"solar\", \"view\" or \"bot

6条回答
  •  不思量自难忘°
    2021-02-07 07:28

    Since functions are objects in python, you could actually process *args as a list of methods and pass the types of simulations as arbitratry args at the end. This would have the benefit of allowing you to define new simulations in the future without having to refactor this code.

    def func(a, b, c, *args):
        for arg in args:
            arg(a, b, c)
    
    def foosim(a, b, c):
        print 'foosim %d' % (a + b + c)
    
    def barsim(a, b, c):
        print 'barsim %d' % (a * b * c)
    

    Use:

    func(2, 2, 3, foosim)
    func(2, 2, 3, barsim)
    func(2, 2, 3, foosim, barsim)
    

    Output:

    foosim 7
    barsim 12
    foosim 7
    barsim 12
    

提交回复
热议问题