python在繼承中,基類的構造函數(init)方法不會被自動調用,它需要在其派生類的構造函數中顯示調用。
比如我需要在BaseHTTPRequestHandler類中做一下初始化工作,比如連接數據庫。
class RequestHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPRequestHandler.__init__(self, request, client_address, server)
try:
self.conn = MySQLdb.connect(host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, \
passwd=MYSQL_PASSWD, db=MYSQL_DB,charset=MYSQL_CHARSET)
except Exception, e:
print e
print 'connect database success'
比如我需要在HTTPServer類中做一下初始化工作,比如連接數據庫。
class MyHTTPServer(HTTPServer):
def __init__(self, server_address, RequestHandlerClass):
HTTPServer.__init__(self, server_address, RequestHandlerClass)
try:
self.conn = MySQLdb.connect(host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, \
passwd=MYSQL_PASSWD, db=MYSQL_DB,charset=MYSQL_CHARSET)
except Exception, e:
print e
print 'connect database success'