【问题标题】:Python Object initialization with two sets of parentheses带有两组括号的 Python 对象初始化
【发布时间】:2018-07-15 17:59:46
【问题描述】:

我刚刚开始使用 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 在这里不返回函数。

完整的代码可以在这里找到

【问题讨论】:

标签: python


【解决方案1】:

看起来Tag 或其他一些基类定义了__call__ 使得标签是可调用的对象。这使得每个标记都可以使用传递给第一组括号中的构造函数的属性(由__init__ 处理)和第二组中传递的标记内容(由__call__ 处理)来构造。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-04
  • 2019-01-12
  • 2018-12-12
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2017-07-24
相关资源
最近更新 更多