[英]Passing a function as a parameter - BeautifulSoup
在BeautifulSoup文檔中,函數定義如下:
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
然后作為參數傳遞給函數: find_all()
:
soup.find_all(has_class_but_no_id)
讓我感到驚訝的是它起作用了。 我真的不知道機制在這里是如何工作的,這個函數( has_class_but_no_id
)怎么能為find_all()
函數返回一個值,而沒有一個參數可以工作?
has_class_but_no_id
傳遞給find_all()
時,它不會執行。
find_all
執行調用has_class_but_no_id
,多次,通過它的標簽,當時的“標簽”的價值。 這是一種利用以下事實的模式:在Python中,函數是所謂的一階對象 - 它們作為對象存在,您可以在變量中傳遞它們。
這允許函數接受其他函數並在以后運行它們 - 就像BeautifulSoup在這里一樣。
嘗試一下實驗:
def say_something(something_to_say):
print something_to_say
def call_another_function(func, argument):
func(argument)
call_another_function(say_something, "hi there")
上面的答案來自這篇Reddit帖子 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.