关于Python html.parser.HTMLParser类构造函数参数的疑问咨询
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 writeHTMLParser(False)to setconvert_charrefstoFalse. You have to explicitly writeHTMLParser(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
objectby default. - This syntax makes instantiating
HTMLParsersafer and more readable, since you have to be explicit about the parameter you’re setting.
内容的提问来源于stack exchange,提问作者Lorenz Hart

