Python中的打印(函数)与打印(函数()

2024-05-23 17:50:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下简单的脚本,它从某个站点获取文本:

from urllib.request import urlopen

def fetch_words():
    contentdownload = urlopen('https://wolnelektury.pl/media/book/txt/treny-tren-viii.txt')
    decluttered = []
    for line in contentdownload:
        decltr_line = line.decode('utf8').split("  ")
        for word in decltr_line:
            decluttered.append(word)
    contentdownload.close()
    return decluttered

在末尾添加:print(fetch_words)时,程序返回:<function fetch_words at 0x7fa440feb200>,但另一方面,当我将其替换为:print(fetch_words())时,它返回网站的内容,即函数下载的内容。 我有以下问题:为什么它是这样工作的,有什么区别:function()还是没有。。。 感谢所有帮助


Tags: intxt脚本内容forlinefunctionfetch
1条回答
网友
1楼 · 发布于 2024-05-23 17:50:40

当您调用print(fetch_words)时,您将得到函数作为对象的表示

def fetch_words():
    pass

isinstance(fetch_words,object)

返回True。实际上,Python中的函数是对象

因此,当您键入print(fetch_words)时,实际上会得到fetch_words.__str__()的结果,这是一种特殊的方法,在打印对象时会调用它

当您键入print(fetch_words())时,您将得到函数的结果(函数返回的值)。因为()执行函数

因此fetch_words是一个对象fetch_words()执行函数,其值是函数返回的值

相关问题 更多 >