小编Gaj*_*uke的帖子

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

我有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()
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我得到以下错误

Traceback (most recent call last):                                                                                
  File "/home/main.py", line 22, in <module>                                                                      
    cust_fun_name()                                                                                               
TypeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)

python function python-3.x

2
推荐指数
1
解决办法
1309
查看次数

标签 统计

function ×1

python ×1

python-3.x ×1