【问题标题】:TypeError: 'str' object is not callable with input()TypeError: 'str' 对象不能用 input() 调用
【发布时间】:2019-05-13 19:19:32
【问题描述】:

我有以下代码,它应该询问用户 2 文件名。我在第二个函数中的 input() 出现错误,但在第一个函数中没有,我不明白...... 这是错误:

输出 = getOutputFile() 文件“splitRAW.py”,第 22 行,在 getOutputFile 文件名 = 输入(“\t=>”) TypeError: 'str' 对象不可调用

# Loops until an existing file has been found
def getInputFile():
    print("Which file do you want to split ?")
    fileName = input("\t=> ")
    while 1:
        try:
            file = open(fileName, "r")
            print("Existing file, let's continue !")
            return(fileName)
        except IOError:
            print("No such existing file...")
            print("Which file do you want to split ?")
            fileName = input("\t=> ")

# Gets an output file from user
def getOutputFile():
    print("What name for the output file ?")
    fileName = input("\t=> ")

这是我的 main() :

if __name__ == "__main__":
    input = getInputFile()
    output = getOutputFile()

【问题讨论】:

  • 在代码中的某处,您定义了input = something_here。根据您的 IDE,它可能位于不同的文件或控制台中
  • 就是这样,谢谢!!

标签: python input error-handling


【解决方案1】:

问题是当你说input = getInputFile()时。

更具体地说:

  1. 程序进入getInputFile()函数,input还没有被赋值。这意味着 Python 解释器将按照您的意图使用内置的 input
  2. 您返回filename 并离开getInputFile()。解释器现在将名称 input 覆盖为该字符串。
  3. getOutputFile() 现在尝试使用 input,但它已被您的文件名字符串替换。您不能调用字符串,因此解释器会告诉您并抛出错误。

尝试将input = getInputFile() 替换为其他变量,例如fileIn = getInputFile()

此外,您的 getOutputFile() 没有返回任何内容,因此您的 output 变量中只会包含 None

【讨论】:

  • 带走信息是,不要命名类似于函数名称的变量。
【解决方案2】:

您可能会用其他内容覆盖输入名称。

如果需要重新初始化笔记本中的输入功能:

from builtin import input

【讨论】:

    【解决方案3】:

    下一次只是“RESTART YOUR KERNEL” TypeError: 'str' object is not callable - 重新启动内核并且它消失了。你可以走了。

    【讨论】:

    • 首先需要将输入的变量名改成其他变量,因为python解释器混淆了,然后重启内核
    【解决方案4】:

    Depending on what version of python you're using:

    Python 2:

    var = raw_input("Please enter something: ")
    print "you entered", var
    

    或者对于 Python 3:

    var = input("Please enter something: ")
    print("You entered: " + var)
    

    【讨论】:

    • 不,这不是问题所在。随着错误的传达,他们践踏了input 内置函数
    猜你喜欢
    • 2015-03-07
    • 2019-03-05
    • 1970-01-01
    • 2023-03-06
    • 2019-01-28
    • 2019-01-10
    • 2020-09-16
    • 2019-06-11
    相关资源
    最近更新 更多