You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Python html.parser.HTMLParser类构造函数参数的疑问咨询

Understanding class html.parser.HTMLParser(*, convert_charrefs=True) Syntax

Hey there! Great catch—this syntax can feel counterintuitive when you’re just starting out with Python, since we’re used to seeing parent classes inside those parentheses. Let’s break this down step by step:

1. The * in Parameters: Keyword-Only Arguments

That lone * is a Python feature called a keyword-only parameter marker. Here’s what it does:

  • Any parameter listed after the * can only be passed using its keyword name—you can’t use positional arguments for them.
  • For HTMLParser, this means you can’t write HTMLParser(False) to set convert_charrefs to False. You have to explicitly write HTMLParser(convert_charrefs=False).

This is designed to make code clearer and avoid mistakes—especially if the class adds more parameters later, your existing code won’t break due to positional argument ordering.

2. Why No Parent Class Listed?

In Python 3, every class implicitly inherits from object (the base class for all Python objects) if no parent class is specified. The official docs omit object here to focus on what matters most for users: the parameters you need to know to instantiate the class.

If you looked at the actual source code for HTMLParser, you’d see it does inherit from object—the docs just simplify the definition to highlight the constructor arguments.

3. Practical Examples

Let’s see valid and invalid ways to instantiate HTMLParser:

  • Valid (default behavior):
    from html.parser import HTMLParser
    parser = HTMLParser()  # Uses convert_charrefs=True automatically
    
  • Valid (explicit keyword argument):
    parser = HTMLParser(convert_charrefs=False)
    
  • Invalid (positional argument won’t work):
    parser = HTMLParser(False)  # Throws a TypeError!
    

Quick Recap

  • The * enforces keyword-only arguments for anything that comes after it.
  • The missing parent class is just a docs simplification—all Python 3 classes inherit from object by default.
  • This syntax makes instantiating HTMLParser safer and more readable, since you have to be explicit about the parameter you’re setting.

内容的提问来源于stack exchange,提问作者Lorenz Hart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:48:11