【问题标题】:Python NoneType object is not callable (beginner)Python NoneType 对象不可调用(初学者)
【发布时间】:2012-04-03 20:40:19
【问题描述】:

它告诉我第 1 行和第 5 行(调试/编程新手,不确定是否有帮助)

def hi():
    print('hi')


def loop(f, n):  # f repeats n times
    if n <= 0:
        return
    else:
        f()
        loop(f, n-1)
>>> loop(hi(), 5)
hi
f()
TypeError: 'NoneType' object is not callable

为什么会出现这个错误?

【问题讨论】:

    标签: python nonetype


    【解决方案1】:

    您希望将函数 object hi 传递给您的 loop() 函数,而不是 调用hi() 的结果(即 None因为hi() 没有返回任何东西)。

    所以试试这个:

    >>> loop(hi, 5)
    hi
    hi
    hi
    hi
    hi
    

    也许这会帮助你更好地理解:

    >>> print hi()
    hi
    None
    >>> print hi
    <function hi at 0x0000000002422648>
    

    【讨论】:

    • 不客气。此外,您可能想要调用您的函数 recurse 或类似的东西,因为它实际上并没有循环......
    【解决方案2】:

    为什么会出现这个错误?

    因为您传递给loop 函数的第一个参数是None,但您的函数需要一个可调用对象,而None 对象不是。

    因此,您必须传递可调用对象,在您的情况下为 hi 函数对象。

    def hi():     
      print 'hi'
    
    def loop(f, n):         #f repeats n times
      if n<=0:
        return
      else:
        f()             
        loop(f, n-1)    
    
    loop(hi, 5)
    

    【讨论】:

    • 如果 hi 函数有一个参数怎么办,例如文本,并打印作为变量文本传递的字符串。怎么处理?
    • 试试lambda arg: hi(arg)
    【解决方案3】:

    您不应该将调用函数 hi() 传递给 loop() 函数,这将给出结果。

    def hi():     
      print('hi')
    
    def loop(f, n):         #f repeats n times
      if n<=0:
        return
      else:
        f()             
        loop(f, n-1)    
    
    loop(hi, 5)            # Do not use hi() function inside loop() function
    

    【讨论】:

      【解决方案4】:

      我遇到了错误“TypeError: 'NoneType' object is not callable”,但问题不同。 有了以上线索,我就可以调试并做对了! 我面临的问题是: 我已经编写了客户库,但我的文件无法识别它,尽管我已经提到了它

      example: 
      Library           ../../../libraries/customlibraries/ExtendedWaitKeywords.py
      the keywords from my custom library were recognized and that error  was resolved only after specifying the complete path, as it was not getting the callable function.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多