我用python编写了一个http服务器程序,我的requesthandler类继承自basehttpserver,它初始化一个成员a,但是在basehttpserver是第一个in i t语句的地方我无法访问它,当我更改init语句顺序时,它将是正确的。

#!/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()

最佳答案

因为请求是在BaseHTTPServer.BaseHTTPRequestHandler.__init__中处理的(确切地说,是超类__init__)。
do_GET方法是在处理请求时调用的;此时,self.a = 0不会执行;导致AttributeError
简而言之,在第一个代码的do_GET行之前调用self.a方法。
RequestHandler.__init__
BaseHTTPServer.BaseHTTPRequestHandler.__init__(..)
...
do_GET
...
self.a = 0

10-08 15:11