我有两个设定选项。用户可以选择test或test1作为设置。如果他选择test,则执行方法test以及方法xytest。
我用映射来调用方法test和test1,这也是可行的。但是,我仍然需要调用第二个方法,即xy<name of mapping method>。是否有一个更好、更优雅的解决方案,用户可以在test和test1之间进行选择,从而得到不同的结果?我的意思是,没有更好的解决方案来绕过这些if语句吗?
def test():
return "Hi"
def xytest():
return "I'm Zoe"
def test1():
return "Hello"
def xytest1():
return "I'm Max"
mapping = {
"test": test,
"test1": test1,
}
def try_method(option):
parameter = mapping[option]()
# How can I shorten both if statements, as in the above call
if option == 'test':
parameter2 = xytest()
if option == 'test1':
parameter2 = xytest1()
# Something like
# parameter2 = 'xy'+mapping[option]()
print(parameter)
print(parameter2)
# the user could only choose between test and test1
try_method('test')发布于 2021-05-26 16:14:29
为了消除if子句,我建议使用稍微不同的mapping。mapping包含可以根据option参数调用的函数列表:
#!/usr/bin/python
def test():
return "Hi"
def xytest():
return "I'm Zoe"
def test1():
return "Hello"
def xytest1():
return "I'm Max"
mapping = {
"test": [ test, xytest ],
"test1": [ test1, xytest1]
}
def try_method(option):
print(mapping[option][0]())
print(mapping[option][1]())
# the user could only choose between test and test1
try_method('test')
try_method('test1')输出:
Hi
I'm Zoe
Hello
I'm Maxhttps://stackoverflow.com/questions/67708379
复制相似问题