首先让我用一些样例来解释 假设有一个Web API客户端模块(MyAPIClient),一个将任意响应转换为Python对象(ObjectMapper)的映射器类,以及一个表示响应对象(用户和消息)的类。
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。"的参数。这是 NOT 类的一个实例,但是一个类本身如 MyAPIClient#get_current_user 和 MyAPIClient#get_message 所示。我的问题是我应该如何在 ObjectMapper #__ init __ 中注释这个mapping_class,它当前被标记为" ???"在上面的示例中。
答案 0 :(得分:2)
类本身是callable,它返回该类的实例。解决方案可以是:
mapping_class: Callable[..., MyResponse]
答案 1 :(得分:0)
使用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)