I'm struggling with some python concepts and can use your help. An example from HTMLparser at https://docs.python.org/3/library/html.parser.html#examples is pasted below:
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Encountered a start tag:", tag)
def handle_endtag(self, tag):
print("Encountered an end tag :", tag)
def handle_data(self, data):
print("Encountered some data :", data)
parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')
Its clear that for some reason, the HTMLParser class is being inherited, and handle_starttag, handle_endtag and handle_data functions are being overridden in the above code.
My questions are:
Why cant the class be used directly? Why does it need to be inherited prior to be used?
How come the output is printing out these tags even though these functions (handle_starttag, handle_data, etc.) are not even being called from somewhere? Unless you call these functions, they will not execute, and will not print out anything. In the above example, only the ".feed" function on the parser object is being called, I don't see any reference to these functions being called anywhere. Yet, when I execute the above code in Spyder, the print statements work!
Please help me understand this.
Thank you, much appreciated!