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

后端 未结 9 1502
臣服心动
臣服心动 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:26

    Ah never mind, this explained it. I was thinking of elif http://bytebaker.com/2008/11/03/switch-case-statement-in-python/

    0 讨论(0)
  • 2020-12-10 21:27

    It sounds like you're complicating this more than you need to. You want simple?

    if mytype == 'create':
        return msg(some_data)
    elif mytype == 'update':
        return msg(other_data)
    else:
        return msg(default_data)
    

    You don't have to use dicts and function references just because you can. Sometimes a boring, explicit if/else block is exactly what you need. It's clear to even the newest programmers on your team and won't call msg() unnecessarily, ever. I'm also willing to bet that this will be faster than the other solution you were working on unless the number of cases grows large and msg() is lightning fast.

    0 讨论(0)
  • 2020-12-10 21:29

    what about creating new class and wrap the data/arguments in object - so instead of binding data by passing arguments - you could just let function decide which parameters it needs...

    class MyObj(object):
            def __init__(self, data, other_data):
                    self.data = data
                    self.other_data = other_data
    
            def switch(self, method_type):
                    return {
                                    "create": self.msg,
                                    "update": self.msg,
                                    "delete": self.delete_func,
                            }[method_type]()
    
            def msg(self):
                    #process self.data
                    return "Hello, World  !!"
    
            def delete_func(self):
                    #process other data self.other_data or anything else....
                    return True
    
    if "__main__" == __name__:
            m1 = MyObj(1,2)
            print m1.switch('create')
            print m1.switch('delete')
    
    0 讨论(0)
提交回复
热议问题