Alternative to overwriting the __init__ function of BaseHTTPRequestHandler

Viewed 585

I would like to define a few variables inside my RequestHandler class that is a subclass of BaseHTTPRequestHandler. These variables then should be accessible from inside my do_Post() function. Normaly I would define those variables inside the __ init__() method but the python docs about the BaseHTTPRequestHandler class

says "Subclasses should not need to override or extend the __ init__() method."

So what would be the most elegant way to achieve this?

from http.server import BaseHTTPRequestHandler, HTTPServer

class RequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        #do some stuff
1 Answers

Shouldn't need to means you don't have to worry about that method, the library will work without any special attributes set on the instance. However, that doesn't mean you can't.

For example, the BaseHTTPRequestHandler class doesn't define a __init__ method itself, but the SimpleHTTPRequestHandler class in the same module is a direct subclass of BaseHTTPRequestHandler which does define an __init__ method.

Your code can define one just fine:

class RequestHandler(BaseHTTPRequestHandler):
    def __init__(self, ...):
        # do something with arguments and set state on self

    def do_POST(self):
        # do some stuff
Related