我想从我的函数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)
您的字典需要将函数名称保存为变量而不是“字符串”:
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")()