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