gpt4 book ai didi

python - PEP0484 类型提示 : Annotating argument of given class, 不是实例

转载 作者:太空宇宙 更新时间:2023-11-03 11:25:37 25 4
gpt4 key购买 nike

让我先用一些例子来解释。
假设有一个 Web API 客户端模块(MyAPIClient),一个将任意响应转换为 Python 对象的映射器类(ObjectMapper),以及一个表示响应对象(User 和 Message)的类。

class User(MyResponse):
def __init__(self, status: int, id: int, name: str) -> None:
super().__init__(status)
self.id = int
self.name = name

class Message(MyResponse):
def __init__(self, status: int, id: int, text: str) -> None:
super().__init__(status)
self.id = int
self.text = name

class ObjectMapper(object):
def __init__(self, mapping_class: ???) -> None:
self.mapping_class = mapping_class

def map(self, obj) -> MyResponse:
return self.mapping_class(**kwargs)

class MyAPIClient(object):
def __init__(self, ...) -> None:
pass

def get_current_user(...) -> User:
self.request("GET", "/current_user", ObjectMapper(User))

def get_message(...) -> Message:
self.request("GET", "/message", ObjectMapper(Message))

def request(method: str, endpoint: str, mapper: ObjectMapper):
res = requests.request(...)
return json.loads(response.content.decode(), object_hook=mapper.map)

如上例所示,ObjectMapper 接收一个名为“mapping_class”的参数。这不是类的实例,而是类本身,如 MyAPIClient#get_current_userMyAPIClient#get_message 所示。我的问题是我应该如何在当前标记为“???”的ObjectMapper#__init__ 中注释此mapping_class。在上面的示例中。

最佳答案

使用Type引用类本身:

class ObjectMapper(object):
def __init__(self, mapping_class: Type[MyResponse]) -> None:
self.mapping_class = mapping_class

def map(self, obj) -> MyResponse:
return self.mapping_class(**kwargs)

关于python - PEP0484 类型提示 : Annotating argument of given class, 不是实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34578383/

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