#!/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()
当我更改__init__
订单时,它更正,为什么?
#!/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()
答案 0 :(得分:4)
因为请求是在BaseHTTPServer.BaseHTTPRequestHandler.__init__
处理的(确切地说,是超类'__init__
)。
do_GET
方法;那时,self.a = 0
没有被执行;导致AttributeError
。
简而言之,do_GET
方法在第一个代码的self.a
行之前调用。
RequestHandler.__init__
BaseHTTPServer.BaseHTTPRequestHandler.__init__(..)
do_GET
self.a = 0