未解析的属性引用 '__self__',属于StartResponse类
类型检查器似乎不太支持对 __self__ 的这种用法,并给出所示的错误。有人能解释这是为什么吗?我知道 WSGIref/types.py 并没有明确地定义 __self__,但我以为 __self__ 是Python(类实例化对象)的默认属性。
from typing import Iterator
from wsgiref import simple_server
from wsgiref.types import StartResponse
class Response:
status: str
start_response: StartResponse
def __init__(self, start_response: StartResponse):
self.start_response = start_response
class Controller:
status: str
start_response: StartResponse
obj_response: Response
def __init__(self, _: dict[str, str], start_response: StartResponse) -> None:
self.obj_response = Response(start_response)
def __iter__(self) -> Iterator[bytes]:
self.obj_response.start_response('200 ok', [('Content-type', 'text/html; charset=utf-8')])
self.status = self.obj_response.start_response.__self__.status
# add the comment "# type: ignore" at the end of the above line, as per suggestion by @jonrsharpe, to suppress the error
print(self.status)
yield b"hello world"
httpd = simple_server.make_server("", 8000, Controller)
httpd.serve_forever()
错误:
Unresolved attribute reference '__self__' for class 'StartResponse'
解决方案
就按这种方式:
class Response:
def __init__(self, start_response):
self.start_response = start_response
self.status = ""
def send(self, status, headers):
self.status = status
self.start_response(status, headers)
# and then
self.obj_response.send('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
print(self.obj_response.status)
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。