繁体   English   中英

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

[英]Using variable from __init__ in another methods of a same class

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

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

码:

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))

错误:

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'

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM