PEP0484 类型提示:注释给定类的参数,而不是实例

Okl*_*mer 8 python types python-3.x

让我先用一些例子来解释。
假设有一个 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)
Run Code Online (Sandbox Code Playgroud)

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

DDR*_*Rpy 15

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)
Run Code Online (Sandbox Code Playgroud)


Mik*_*mov 2

类本身是可调用的,它返回该类的实例。解决方案可以是:

mapping_class: Callable[..., MyResponse]
Run Code Online (Sandbox Code Playgroud)