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:<
Ah never mind, this explained it. I was thinking of elif http://bytebaker.com/2008/11/03/switch-case-statement-in-python/
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.
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')