有参数的函数怎么能在没有参数的情况下调用呢

2024-09-30 10:34:01 发布

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

从下面的代码可以看出,mysearch是无参数调用的。这个函数调用怎么可能?这种技术叫什么?方法从何处获取其参数(标记)?对不起,我到处都找不到答案。。。你知道吗

def myserach(tag):
    return tag.has_attr('ResultsAd') # and tag['li']

with open('index.html', 'rb') as file:
    soup = BeautifulSoup(file, "html.parser")

elements1 = soup.find_all('div', attrs={"class": "ResultsAd"})
elements1 = soup.find_all(myserach)

Tags: 方法代码参数htmltagallfind技术
3条回答

它不是“调用一个函数”,而是将一个函数名(C terma中的函数指针)作为参数传递给另一个函数,该函数稍后将使用适当数量的参数调用它。你知道吗

elements1 = soup.find_all(my_search)这一行中,您没有调用my_search,而是将my_search函数传递给soup.find_all函数。你知道吗

注意:可以使用keyword arguments调用函数而不传递其参数。比如:

def my_fun(value=5):
    print(value)

可以通过两种方式调用此函数:

my_fun(10) #here value will be 10
my_fun() #here value will be 5

在代码段中未调用该函数。你知道吗

也许这个例子能帮助你更好地理解。你知道吗

def foo(str):
    print(str)

def bar(arg):
    arg("now calling foo")

bar(foo)

相关问题 更多 >

    热门问题