在同一个类的另一个方法中使用__init__中的变量

时间:2016-03-21 20:41:04

标签: python class methods httpserver basehttprequesthandler

我试图在 init 中创建一个变量,但在同一个类的其他方法中无法识别它。

我不知道为什么self.myvarlol在send_myheaders()中没有正常工作:S

CODE:

from http.server import HTTPServer, BaseHTTPRequestHandler
import time

class myserveromg(BaseHTTPRequestHandler):

    def __init__(self, a, b, c):
        BaseHTTPRequestHandler.__init__(self, a, b, c)
        self.myvarlol = "asdf"
        self.date = self.date_time_string()


    def send_my_headers(self):
        self.send_header("Content-type", "text/html")
        self.send_header("Date", self.date)
        self.end_headers()

    def do_GET(self):
        self.send_response_only(200)
        self.send_my_headers()
        self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>", "utf-8"))
        self.wfile.write(bytes("<body><p>This is a test. </p>", "utf-8"))
        self.wfile.write(bytes("<p>You accessed path: %s</p>" % self.path, "utf-8"))
        self.wfile.write(bytes("</body></html>", "utf-8"))


if __name__ == "__main__":
    hostName = "localhost"
    hostPort = 9000

    appPortal = myserveromg
    myServer = HTTPServer((hostName, hostPort), appPortal)

    try:
        print(time.asctime(), "Server Starts - %s:%s" % (hostName, hostPort))
        myServer.serve_forever()
    except KeyboardInterrupt:
        pass

    myServer.server_close()
    print(time.asctime(), "Server Stops - %s:%s" % (hostName, hostPort))

ERROR:

File "C:\Users\Anonym-PC\Desktop\nuseke.py", line 14, in send_my_headers
    self.send_header("Date", self.date)
AttributeError: 'myserveromg' object has no attribute 'date'

1 个答案:

答案 0 :(得分:4)

你说appPortal = myserveromg,但这只是创建一个别名。 appPortal现在与myserveromg相同:一个类。您需要创建一个调用__init__并定义date的实例。为此,请添加括号:

appPortal = myserveromg(a, b, c) # a, b, and c will need to be defined earlier on.