难以理解将结果传递给另一个函数与将结果重新传递给另一个函数之间的区别

时间:2018-11-22 05:04:31

标签: python python-3.x function web-scraping return

我已经使用两个函数在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)

2 个答案:

答案 0 :(得分:1)

return get_info(elem)

将调用get_info()函数,然后获取返回的任何内容,并从get_links()返回相同的值。大致相当于:

temp = get_info(elem)
return temp

但是由于get_info()不返回任何内容,它仅打印链接,因此在return语句中使用链接没有多大意义。只是写

get_info(elem)

调用函数时不对其返回值进行任何操作(如果返回了任何内容)。

答案 1 :(得分:1)

让我们首先简化您的功能,以便您可以运行它并比较结果:

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* 

如果实际执行某项操作,则返回的结果会更加明显,例如:

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,则仅表示该函数将不返回任何内容,例如,如果您只想像以前那样print返回结果,则会发生这种情况。您可以通过像上面一样为函数分配名称来进一步尝试此方法,该函数没有返回值,并且结果基本上是None

相关问题