Создание переключателя Python, который вызывает функции - PullRequest
0 голосов
/ 17 февраля 2019

Я хочу выбрать из своей функции numbers_to_month и вернуть соответствующую строку (например, январь).Каков наилучший способ сделать это?Я попытался присвоить переменную 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 голосов
/ 17 февраля 2019

Ваш словарь должен содержать имена функций как переменные, а не как "строки":

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)() 

или

def numbers_to_months(argument):
    switcher = { 1:  one, 2:  two, 3:  three, }
    return switcher.get(argument, lambda: "Invalid Month")() 
...