3
我在python寫了一個HTTP服務器程序,我RequestHandler類繼承BaseHTTPServer,它初始化成員的,但在那裏BaseHTTPServer是第一個初始化語句,當我改變了初始化語句中的順序,這將是正確的,我不能訪問它。我無法通過繼承python中的BaseHTTPServer訪問成員,爲什麼?
#!/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()
感謝您的解釋:) – 5he1lc0de 2014-09-22 14:04:26