为什么 Python BeautifulSoup 对象是可调用的?定义在哪里?

Why Python BeautifulSoup object is callable? Where is the definition?

下面代码中的bb和cc是相等的,为什么会这样呢? soup是一个对象,为什么这里可以接受另一个参数'a'? soup('a') 是函数调用还是另一个 class/object 初始化?如果是函数调用,我在class里面没有找到call的定义。我希望问题很清楚。谢谢。

from bs4 import BeautifulSoup
soup = BeautifulSoup("<html><a href='bla'>sss</a><a>cc</a></html>", 'html.parser')
bb = soup('a')
cc = soup.find_all('a')

嗯,其实没什么区别,调用tagalias for findAll

勾选source code

def __call__(self, *args, **kwargs):
    """Calling a tag like a function is the same as calling its
    find_all() method. Eg. tag('a') returns a list of all the A tags
    found within this tag."""
    return self.find_all(*args, **kwargs)

几乎 developers 之所以使用 findAll 是因为它实际上更具可读性。