I cant access member from BaseHTTPServer inheritance in python, why?
I wrote a http server program in python, my RequestHandler class inherits from BaseHTTPServer, it initializes the a member, but I cannot access it, where BaseHTTPServer is the first init statement, when I change the order of the init statements it will be correct.
#!/usr/bin/env python
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)
self.a = 0
print 'aaaa'
def do_GET(self):
print self.a # will cause exception
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
server_address = ('127.0.0.1', 8080)
server_class = BaseHTTPServer.HTTPServer
handler_class = RequestHandler
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
when i changed the order __init__
it is correct why?
#!/usr/bin/env python
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
# change init order
print 'aaaa'
self.a = 0
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)
def do_GET(self):
print self.a # I got
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
server_address = ('127.0.0.1', 8080)
server_class = BaseHTTPServer.HTTPServer
handler_class = RequestHandler
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
source to share
Since the request is processed in BaseHTTPServer.BaseHTTPRequestHandler.__init__
(more precisely, the superclass' __init__
).
do_GET
Called when a request is being processed; At that time self.a = 0
it is not executed; call AttributeError
.
In short, the method do_GET
is called before the line self.a
for the first code.
-
RequestHandler.__init__
-
BaseHTTPServer.BaseHTTPRequestHandler.__init__(..)
- ...
-
do_GET
- ...
-
self.a = 0
-
source to share