我有以下简单的脚本,它从某个站点获取文本:
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和()是否.所有的帮助感谢!!
发布于 2020-05-12 16:57:52
调用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()执行函数,它的值是函数返回的值。
https://stackoverflow.com/questions/61756725
复制相似问题