switch case in python doesn't work; need another pattern

后端 未结 9 1524
臣服心动
臣服心动 2020-12-10 20:28

I need a help with a code here, i wanted to implement the switch case pattern in python so like some tutorial said , i can use a dictionary for that but here is my problem:<

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 21:24

    You could hide the evaluation inside a lambda:

    message = { 'create': lambda: msg(some_data),
                'update': lambda: msg(other_data),
              }
    return message[type]()
    

    As long as the names are all defined (so you don’t get a NameError), you could also structure it like this:

    message = { 'create': (msg, some_data),
                'update': (other_func, other_data),
              }
    func, arg = message[type]
    return func(arg)
    

提交回复
热议问题