python中输入函数,我如何使用用户输入来调用Python中的函数?

本文介绍了在Python中尝试通过字符串调用函数时遇到的错误,即`'str' object is not callable`。错误产生的原因是尝试将函数名当作字符串来调用。解决方法是创建一个字典,将函数名映射到对应的函数引用,然后使用字典的`.get()`方法来调用用户选择的函数。如果输入的函数名无效,可以设置默认处理函数。该文章对于理解和修复Python中与函数调用相关的错误具有指导意义。
摘要由CSDN通过智能技术生成

I have several functions such as:

def func1():

print 'func1'

def func2():

print 'func2'

def func3():

print 'func3'

Then I ask the user to input what function they want to run using choice = raw_input() and try to invoke the function they choose using choice(). If the user input func1 rather than invoking that function it gives me an error that says 'str' object is not callable. Is their anyway for me to turn 'choice' into a callable value?

解决方案

The error is because function names are not string you can't call function like 'func1'() it should be func1(),

You can do like:

{

'func1': func1,

'func2': func2,

'func3': func3,

}.get(choice)()

its by mapping string to function references

side note: you can write a default function like:

def notAfun():

print "not a valid function name"

and improve you code like:

{

'func1': func1,

'func2': func2,

'func3': func3,

}.get(choice, notAfun)()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值