PEP0484 类型提示:注释给定类的参数,而不是实例 [英] PEP0484 Type Hinting: Annotating argument of given class, not instance

查看:22
本文介绍了PEP0484 类型提示:注释给定类的参数,而不是实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let me explain with some sample, first.
Suppose there is a web API client module (MyAPIClient), a mapper class that converts arbitrary response into Python object (ObjectMapper), and a class that represents response object (User and 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在上面的示例中.

As shown in the sample above, ObjectMapper receives an argument named "mapping_class." This is NOT an instance of the class, but a class itself as shown in MyAPIClient#get_current_user and MyAPIClient#get_message. My question is how I should annotate this mapping_class in the ObjectMapper#__init__ which is currently marked as "???" in the sample above.

推荐答案

使用 输入来引用类本身:

Use Type to refer to classes themselves:

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)

这篇关于PEP0484 类型提示:注释给定类的参数,而不是实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆