【问题标题】:python error "typeerror: nonetype object not callable"python错误“类型错误:不可调用的非类型对象”
【发布时间】:2015-10-20 14:11:32
【问题描述】:

我正在尝试在 python 中制作一个简单的计时器脚本。我看到很多其他人也有这个错误,但我认为我的错误可能会有所不同,因为我是 python 新手:

time=60
from time import sleep
while (time>0):
    print ("you have") (time) ("seconds left")
    time-=1
    sleep(1)

结果如下:

>>> you have Traceback (most recent call last): File "H:\counter.py", line 4, in <module> print ("you have") (time) ("seconds left") TypeError: 'NoneType' object is not callable

谁能发现这个错误? 使用 %s 以及在时间变量周围使用 +'s 和 str() 也让我失败了

【问题讨论】:

    标签: python nonetype


    【解决方案1】:

    一个函数只能有一组参数。

    print_statement = "you have" + str(time) + "seconds left"
    print(print_statement)
    

    上面的代码应该可以工作。

    【讨论】:

    • @dioretsa:如果对你有帮助,请接受我的回答:)
    【解决方案2】:

    您对print 函数使用了错误的语法。请注意, 中的 print 是可调用的。因此,当您调用它时,您可以将所有需要打印的内容作为参数传递。

    因此

    print ("you have", time, "seconds left")
    

    是正确的语法。您还可以选择指定分隔符。


    对于后代,TypeError: 'NoneType' object is not callable 是当您尝试使用 NoneType object 作为 callable 时引发的错误。当 Python 发现您尝试将 time(一个 object)传递给 print ("you have") 时它会被标记出来,而 print ("you have") 返回一个 NoneTypeobject。

    记住, print 是一个 callable 并且它本质上返回一个 NullType object (这根本不是什么,因此不可调用)。

    【讨论】:

    • 即使是python2,语法也是错误的,应该是print ("you have"), (time), ("seconds left")。 dioretsa 的 print 几乎看起来像 haskell 函数调用
    • @Lærne 确实如此。 :D。它也是python-2print中元组打包和解包的一个很好的例子。我只写了python-3 的参考,因为这就是我对原始代码语言的看法。 python-2 print 并不真正要求将单个参数放在括号内(似乎过多并促进不良做法)。
    猜你喜欢
    • 2021-02-23
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2020-04-18
    相关资源
    最近更新 更多