我有以下简单的脚本,它从某个站点获取文本:
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
有()
还是没有。。。
感谢所有帮助强>
当您调用
print(fetch_words)
时,您将得到函数作为对象的表示返回
True
。实际上,Python中的函数是对象因此,当您键入
print(fetch_words)
时,实际上会得到fetch_words.__str__()
的结果,这是一种特殊的方法,在打印对象时会调用它当您键入
print(fetch_words())
时,您将得到函数的结果(函数返回的值)。因为()
执行函数因此
fetch_words
是一个对象fetch_words()
执行函数,其值是函数返回的值相关问题 更多 >
编程相关推荐