在类方法中,我为单个关键字参数提供了一组可能的选项,每个选项都有不同的算法来计算某些东西。为了检查哪个选项已添加到关键字中,我制作了一条链,if,elif,否则也找到提供的关键字选项。
class MyClass:
def my_method(self, my_parameter, my_keyword='spacial'):
if my_keyword == 'spacial':
print('Cool stuf')
elif my_keyword == 'discoidal':
print('OTHER cool stuff')
elif my_keyword == 'temporal':
print('You get the gist')
else:
print('not in options list')
在我看来,这不是一种非常优雅的编码方式。特别是如果选项列表不断增长。有没有办法省略 if、elif、elif、else 语句的列表?
使用字典:
def cool_stuff(param):
...
def other_cool_stuff(param):
...
def you_get_the_gist(param):
....
dispatch_mapping = {
'spacial': cool_stuff,
'discoidal': other_cool_stuff,
'temporal': you_get_the_gist
}
别处:
def my_method(self, param, keyword='spacial'):
handler = dispatch_mapping.get(keyword)
if handler is None:
raise Exception("No handler for %s" % keyword)
return handler(param)
总有一个地方必须划分案例。
在您的情况下,您设置了一个字符串,然后再次比较它。
解决这个问题的"方法"是直接通过不同的函数/方法调用替换字符串设置,而不是在函数中路由它。或者使用字典将字符串映射到函数调用。
使用字典是个好主意。但是,另一个选项是反射由字符串调用的函数。
class MyClass:
def handle_spacial(self):
print('Cool stuf')
def handle_discoidal(self):
print('OTHER cool stuff')
def handle_temporal(self):
print('You get the gist')
def default(self):
print('not in options list')
def my_method(self, my_parameter, my_keyword='spacial'):
function_name = "handle_"+my_keyword
if hasattr(self, function_name):
getattr(self, function_name)()
else:
self.default()
创建要按以下方式显示和使用关键字和选项字典的最佳方法:
>>> class MyClass:
... global mykey_option
... mykey_option={'spacial':'Cool stuf','discoidal':'OTHER cool stuff','temporal':'You get the gist'}
... def my_method(self, my_parameter, my_keyword='spacial'):
... try:
... print(mykey_option[my_keyword])
... except:
... print('not in options list')
...
>>> x = MyClass()
>>> x.my_method(1,'discoidal')
OTHER cool stuff
>>> x.my_method(1,'spacial')
Cool stuf
>>> x.my_method(1,'temporal')
You get the gist
>>> x.my_method(1,'newstring')
not in options list