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

标签 python python-3.x types

让我先用一些例子来解释。
假设有一个 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/

相关文章:

python - 使 Tkinter Notebook 可拖动

python Pandas : How fill date ranges in a multiindex

python - 为什么我的代码无法使日期时间对象识别时区?

c++ - sympy ccode 数字类型

json - 如何在 Flutter 中转换 json 空数组?

Haskell 类型和模式匹配问题 : extracting fields from a data type

python - 在 Python 中使用相互或循环(循环)导入时会发生什么?

python - 与 Django 一起使用的 virtualenv python3 中的 psycopg2 出现问题

python-3.x - pandas 中非结构化数据的处理

python - 根据函数中参数的数量返回不同的值