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

后端 未结 9 1526
臣服心动
臣服心动 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: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')
    

提交回复
热议问题