我有10到20个具有相同前缀名称的函数,并且我必须根据用户输入来调用它们,但是没有得到如何调用它们的方法,我尝试使用下面的方法,但是它不起作用,谁能告诉我应该怎么做我使函数可调用。
def pattern_1(no):
print('First Pattern with ' +str(no)+ ' rows')
def pattern_2(no):
print('Second Pattern with ' +str(no)+ ' rows')
rows = eval(input('Enter number of rows: '))
pattern_no = eval(input('Enter pattern num [1-10]: '))
cust_fun_name = 'pattern_' + str(pattern_no)
print(cust_fun_name) # Here its print pattern_2 but why function is not get invoked
cust_fun_name()
当我在上面的代码中运行时,出现以下错误
Traceback (most recent call last):
File "/home/main.py", line 22, in <module>
cust_fun_name()
TypeError: 'str' object is not callable
答案 0 :(得分:6)
如果映射是静态的,则可以将函数名称映射到函数对象
mapping = {
"pattern_1": pattern_1,
"pattern_2": pattern_2
}
#do not use `eval` on user input!
pattern_no = input('Enter pattern num [1-10]: ')
cust_fun_name = 'pattern_' + str(pattern_no)
cust_func = mapping[cust_fun_name]
# call the function
cust_func()
或直接从本地名称空间获取功能对象
cust_func = locals()['pattern_' + str(pattern_no)]
cust_func()
答案 1 :(得分:0)
如果您确实想这样做,可以使用eval()
:
def pattern_1(no):
print('First Pattern with ' +str(no)+ ' rows')
def pattern_2(no):
print('Second Pattern with ' +str(no)+ ' rows')
rows = input('Enter number of rows: ')
pattern_no = input('Enter pattern num [1-10]: ')
cust_fun_name = 'pattern_' + pattern_no
print(cust_fun_name)
eval(cust_fun_name+"("+rows+")") # This is how you use eval()
# Enter number of rows: >? 10
# Enter pattern num [1-10]: >? 1
# pattern_1
# First Pattern with 10 rows
但是,我认为您应该遵循Robin的回答,这是使用Python的合法方法。
答案 2 :(得分:0)
def pattern_1(no):
print('First Pattern with ' +str(no)+ ' rows')
def pattern_2(no):
print('Second Pattern with ' +str(no)+ ' rows')
rows = eval(input('Enter number of rows: '))
pattern_no = eval(input('Enter pattern num [1-10]: '))
pattern_2(no)
cust_fun_name = 'pattern_' + str(pattern_no)
print(cust_fun_name) # Here its print pattern_2 but why function is not get invoked
eval(cust_fun_name)()