如何生成动态函数名称并使用Python中的用户输入调用它

问题描述 投票:2回答:3

我有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
python python-3.x function
3个回答
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()

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

但是,我认为你应该遵循罗宾的回答,这是使用Python的合法方式。


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)()
© www.soinside.com 2019 - 2024. All rights reserved.