在python3中,为什么将“输入”解释为字符串?

时间:2018-10-14 01:59:06

标签: python function

如果我将此代码放在主程序中,它将运行良好:

print("type of input=", type(input))
c = input('Enter q to quit, anything else to 
continue\n:') 
if (c.lower()=='q'): sys.exit()

,并且如预期的那样,它说“输入”是一个内置函数。

但是,如果将其放在函数中,则会出现一个奇怪的错误:

def pause():
    print("type of input=", type(input))
    c = input('Enter q to quit, anything else to continue\n:') 
    if (c.lower()=='q'): sys.exit()
    return (c)

这会打印出'input'是字符串类型,然后用

TypeError: 'str' object is not callable

暂停功能是导入后程序中的第一件事。

您知道什么可能导致此问题吗?

如果我将暂停功能放在文件的末尾,然后将“ main”更改为一个函数,并在定义暂停后调用它,那么一切都会很好。

2 个答案:

答案 0 :(得分:2)

如果调用input()告诉您str is not a callable,则意味着您已在代码中更早的位置用字符串覆盖了input

答案 1 :(得分:0)

@John的权利,在某处必须input作为变量或其他内容,改写不是一件好事,因此,如果要保持以前的状态(但以后将无法再使用):

input = ...
...
del input
# back to regular input
inp=input(...)# works

或保留input变量,请执行以下操作:

...
inp=__builtins__.input(...)

这很好,因为仍然可以访问先前的input变量,并且可以对真实的__builtins__执行input的{​​{1}}