构建一个调用函数的python开关

时间:2019-02-17 16:18:38

标签: python-3.x switch-statement

我想从函数numbers_to_month中选择并返回适当的字符串(例如January)。做这个的最好方式是什么? 我尝试将变量分配给numbers_to_month。例如

>>> test = numbers_to_months(1)
one

但是,当我调用该变量时,我期望适当的月份,但出现错误。例如

>>> test()
Traceback (most recent call last):
  File "<pyshell#96>", line 1, in <module>
    test()
TypeError: 'NoneType' object is not callable

我的代码:

def one():
    return "January"

def two():
    return "February"

def three():
    return "March"

def four():
    return "April"

def five():
    return "May"

def six():
    return "June"

def seven():
    return "July"

def eight():
    return "August"

def nine():
    return "September"

def ten():
    return "October"

def eleven():
    return "November"

def twelve():
    return "December"

def numbers_to_months(argument):
    switcher = {
        1: "one",
        2: "two",
        3: "three",
        4: "four",
        5: "five",
        6: "six",
        7: "seven",
        8: "eight",
        9: "nine",
        10: "ten",
        11: "eleven",
        12: "twelve"
        }
    # Get the function from the switcher dictionary
    func = switcher.get(argument, lambda: "Invalid Month")
    # Execute the function
    print(func)

1 个答案:

答案 0 :(得分:0)

您的字典需要将函数名称保存为变量,而不是“字符串”:

PATH_TO_GOOGLE_PLISTS="${PROJECT_DIR}/MobileToken"

if [ "${CONFIGURATION}" = "CustomDebug1" ]; then
    echo "CustomDebug1"
fi

if [ "${CONFIGURATION}" = "CustomDebug2" ]; then
    echo "CustomDebug2"
fi

if [ "${CONFIGURATION}" = "CustomRelease1" ]; then
    echo "CustomRelease1"
fi

if [ "${CONFIGURATION}" = "CustomRelease2" ]; then
    echo "CustomRelease2"
fi

您可以做的更短:

def one():    return "January"
def two():    return "February"
def three():  return "March" 
# snipp the remaining ones

def numbers_to_months(argument):
    # this indirection is not justified by any means, simply
    # map to the correct string directly instead of to a function
    # that returns the string if you call it...
    # you have to reference the function-name - not a string of it...
    switcher = { 1:  one, 2:  two, 3:  three, }

    # Get the function from the switcher dictionary
    func = switcher.get(argument)

    # return the result of _calling_ the func or default text
    return func() if func else "Invalid Month" 

for n in range(5):
    print(n, numbers_to_months(n)) 

0 Invalid Month
1 January
2 February
3 March
4 Invalid Month

def numbers_to_months(argument):
    def invalid(): 
        return "Invalid Month"

    switcher = { 1:  one, 2:  two, 3:  three, }
    return switcher.get(argument, invalid)()