代码之家  ›  专栏  ›  技术社区  ›  user1067305

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

  •  -1
  • user1067305  · 技术社区  · 8 年前

    如果我把这段代码放在主程序中,它运行得很好:

    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”是string类型,然后用

    TypeError: 'str' object is not callable
    

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

    知道是什么导致了这个问题吗?

    如果我将pause函数放在文件的末尾,并将'main'改为一个函数,在pause的定义之后调用它,那么一切都正常。

    2 回复  |  直到 8 年前
        1
  •  2
  •   John Zwinck    8 年前

    如果打电话 input() 告诉你了 str is not a callable input 在代码前面的某个地方有一个字符串。

        2
  •  0
  •   U13-Forward    8 年前

    input 作为变量之类的东西,重写不是一件好事,所以如果想保持之前的状态(但之后就再也无法访问它了):

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

    或保持

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

    这是好的,因为仍然可以访问以前的 输入 变量,并执行 __builtins__ 的 真的吗 输入