Python 为用户创建设置选项的优雅解决方案

Python 为用户创建设置选项的优雅解决方案,python,Python,我有两个设置选项。用户可以选择test或test1作为设置。如果他选择test,则执行方法test,同时执行方法xytest 我使用映射调用方法test和test1,这同样有效。但是,我仍然需要调用第二个方法,即xy。是否有更好、更优雅的解决方案,用户可以在test和test1之间进行选择,并相应地得到不同的结果?我的意思是,没有更好的解决方案来绕过这些if语句吗 def test(): return "Hi" def xytest(): return "

我有两个设置选项。用户可以选择
test
test1
作为设置。如果他选择
test
,则执行方法
test
,同时执行方法
xytest

我使用映射调用方法
test
test1
,这同样有效。但是,我仍然需要调用第二个方法,即
xy
。是否有更好、更优雅的解决方案,用户可以在
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')

为了摆脱
if
子句,我建议使用稍微不同的
映射。
映射
包含可根据
选项调用的函数列表
参数:

#!/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 Max

好像是。你能提供一些真实的例子吗?不知道为什么你不直接映射到一个调用
test
xytest
的函数,以及另一个调用
test1
xytest1
的函数。问题是,与本例相比,这些方法本质上更复杂,嵌套程度更高,所以必须保留两个方法。函数返回的值与这些字符串不同,这只是为了说明,以便您可以看到它们有两个不同的值,或者所有方法返回的值都不同。我不知道xy问题应该出现在哪里。我特别想问的是,如何避免这个if语句,并使用methodtest或test1进行准确的调用非常感谢您的回答。这对我帮助很大。我非常感激。