我刚开始使用Python并且一直在研究特定库的代码。该库包含一个Html
类,其初始化如下所示
page = Html()( # add tags inside the one you created calling the parent
Head()( # add multiple tags in one call
Meta(charset='utf-8'), # add tag attributes using kwargs in tag initialization
Link(href="my.css", typ="text/css", rel="stylesheet")
),
body=Body()( # give them a name so you can navigate the DOM with those names
Div(klass='linkBox')(
A(href='www.foo.com')
),
(P()(text) for text in my_text_list), # tag insertion accepts generators
another_list # add text from a list, str.join is used in rendering
)
)
,类定义如下所示
class Html(Tag):
"""Html tag have a custom render method for it needs to output the Doctype tag outside the main page tree.
Every Html object is associated with a Doctype object (default doctype code: 'html').
"""
__tag = 'html'
def __init__(self, *args, **kwargs):
# Setting a default doctype: 'html'
doctype = kwargs.pop('doctype', 'html')
super().__init__(**kwargs)
self.doctype = Doctype(doctype)
我的问题是为什么Html
对象初始化需要第二组括号? init不会在这里返回一个函数。
完整的代码可以在这里找到
答案 0 :(得分:3)
看起来Tag
或其他一些基类定义了__call__
,这样标记就是可调用对象。这样就可以使用传递给第一组括号中的构造函数的属性构造每个标记(由__init__
处理),并在第二组中传递标记内容(由__call__
处理)。