调用函数的函数;为什么这个 return NoneType 而不是读取文件?

Function calling a function; why does this return NoneType instead of reading file?

在阅读了 Pydoc 中的文件对象以及函数如何调用函数之后,我重写了 Zed Shaw 的一个 LPTHW 脚本以试图了解它是如何工作的。

代码如下:

def open_file(f):
    open(f)

def read_file(f):
    f.read()

read_file(open_file('test.txt'))

这里是错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in read_file
AttributeError: 'NoneType' object has no attribute 'read'

然而这很好用:

input_file = 'test.txt'

print open(input_file).read()

为什么函数调用函数版本 return NoneType 而不是读取文件?

您的 open_file() 函数实际上 return 没有任何作用。你要的是:

def open_file(f):
    return open(f)

一个函数在没有显式 return 值 returns None 的情况下到达终点,所以你得到异常是因为你的代码正在尝试执行 read_file(None),它会依次尝试执行 None.read()None 对象没有 read() 方法。

答案如下:

def open_file(f):
    return open(f)

def read_file(f):
    print f.read()

read_file(open_file('test.txt'))

给出以下输出:

Mary had a little lamb.
Its fleece was white as snow.
It was also very tasty.