我用 python 编写了一个脚本,其中使用了两个函数。第一个函数应该从网页获取一些链接,另一个函数应该在控制台中打印它。
我的问题是,当我使用 return
关键字(如 return get_info(elem)
)将结果从一个函数传递到另一个函数时,会有什么区别?通常只执行此 get_info(elem)
,我可以将内容从一个函数传递到另一个函数,然后何时选择此 return get_info(elem)
以及为什么?
一个例子可能是:
import requests
from bs4 import BeautifulSoup
def get_links(url):
response = requests.get(url)
soup = BeautifulSoup(response.text,"lxml")
elem = soup.select_one(".info h2 a[data-analytics]").get("href")
get_info(elem) #why this one
return get_info(elem) #or why this
def get_info(link):
print(link)
最佳答案
让我们首先简化您的函数,以便您可以运行它并比较结果:
def get_links(url):
url = "this returns link: {}".format(url)
get_info(url) #why this one
return get_info(url) #or why this
def get_info(link):
print(link)
get_links('google.com')
>>this returns link: google.com
>>this returns link: google.com
您的函数现在返回 print
两次。首先是当您调用该函数时,其次是当您返回该函数时,在这种情况下实际上返回 None
因为 get_info
不返回任何内容。
这在这里很明显:
url = get_links('google.com')
>>this returns link: google.com
>>this returns link: google.com
url
>> *nothing happens*
如果 return 确实做了一些事情,那么它的结果会更加明显,例如:
def get_links(url):
url = "this returns link: {}".format(url)
return get_info(url)
def get_info(link):
return "get_info does something, {}".format(link)
url = get_links('google.com')
url
>>'get_info does something, this returns link: google.com'
如果您不使用 return,则仅意味着该函数不会返回任何内容,例如,如果您只想像您一样打印
结果,就会发生这种情况。您可以通过像上面那样为没有返回的函数分配一个名称来进一步尝试这一点,结果基本上是 None
。
关于python - 难以理解将结果传递给另一个函数和将结果返回给另一个函数之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53424187/