gpt4 book ai didi

python - 在同一类的另一个方法中使用来自 __init__ 的变量

转载 作者:太空宇宙 更新时间:2023-11-04 10:14:42 25 4
gpt4 key购买 nike

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

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

代码:

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.

关于python - 在同一类的另一个方法中使用来自 __init__ 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36141153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com