【问题标题】:Recursive function returns None [duplicate]递归函数返回无[重复]
【发布时间】:2020-11-06 22:59:40
【问题描述】:

我正在使用递归函数来获取每个目录中的文件大小,但得到 TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'。但是我检查了所有子目录中的所有文件,我没有看到任何文件返回 None 类型:

import os
def disk_usage(path):
    """
    this function resursiverly check file size in each diretory and return size of 
    path/directory
    provided.
    """
    total = os.path.getsize(path)
    if os.path.isdir(path):
        for file in os.listdir(path):
            subdir = os.path.join(path, file)
            print(subdir)
            total +=disk_usage(subdir)
    print ("{} for path {}".format(total, path))
path = "/home/akjha/Documents/Aashutosh_cfengine/"
disk_usage(path)

【问题讨论】:

标签: python recursion


【解决方案1】:

disk_usage末尾需要添加

return total

否则,如果没有 return 语句,它将隐含 return None,这将导致

total += disk_usage(subdir)

int 添加到None

【讨论】:

    【解决方案2】:

    你的方法disk_usage() 没有返回任何东西。在 python 中,没有显式返回的方法默认返回None

    当你递归调用时

    total +=disk_usage(subdir)
    

    disk_usage(subdir) 返回None,这会产生您的错误。

    解决办法:放

    return total
    

    在函数的末尾,在去缩进之前。

    【讨论】:

      猜你喜欢
      • 2020-08-24
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2022-06-29
      • 2017-06-19
      • 2014-04-14
      • 2022-08-13
      相关资源
      最近更新 更多