You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为返回抽象类实现结果类型的方法正确添加类型提示

问题描述

我在为方法的返回结果添加类型提示时遇到了问题。该方法向服务器发送操作,收到响应后返回解析后的操作结果。每个ServerOperation都有专属的结果类型,我需要获取该类型。

当前代码:

def send(self, operation: ServerOperation): # 此处应如何声明返回类型?
    command = operation.get_command(self.__request_executor.conventions)
    self.__request_executor.execute_command(command)

    if isinstance(operation, ServerOperation):
        return command.result

相关类定义:

ServerOperation类

class ServerOperation(Generic[T]):
    @abstractmethod
    def get_command(self, conventions: "DocumentConventions") -> RavenCommand[T]:
        raise NotImplementedError()

RavenCommand类(简化版)

class RavenCommand(Generic[ResultClass]):
    def __init__(self, result_class: Type[ResultClass] = None):
        self._result_class = result_class
        self.result: Union[None, ResultClass] = None

实现示例:

class GetClientConfigurationOperation(MaintenanceOperation):
    def get_command(self, conventions: "DocumentConventions") -> "RavenCommand[GetClientConfigurationOperation.Result]":
        return self.GetClientConfigurationCommand()

    class GetClientConfigurationCommand(RavenCommand):
        def __init__(self):
            super().__init__(GetClientConfigurationOperation.Result)

        def is_read_request(self) -> bool:
            return False

        def create_request(self, node: ServerNode) -> requests.Request:
            return requests.Request(method="GET", url=f"{node.url}/databases/{node.database}/configuration/client")

        def set_response(self, response: str, from_cache: bool) -> None:
            if response is None:
                return
            self.result = GetClientConfigurationOperation.Result.from_json(json.loads(response))

    class Result:
        def __init__(self, etag: int, configuration: ClientConfiguration):
            self.etag = etag
            self.configuration = configuration

        @staticmethod
        def from_json(json_dict: dict) -> GetClientConfigurationOperation.Result:
            return GetClientConfigurationOperation.Result(
                json_dict["Etag"], ClientConfiguration.from_json(json_dict["Configuration"])
            )
解决方案

要正确为send方法添加返回类型提示,只需利用ServerOperation的泛型参数绑定结果类型,具体步骤如下:

  1. 为send方法引入泛型参数
    定义一个类型变量T,将operation参数的类型指定为ServerOperation[T],这样类型检查器就能关联操作对应的结果类型。

  2. 指定返回类型为Optional[T]
    由于RavenCommand.result的类型是Union[None, ResultClass],对应到ServerOperation的泛型T,返回类型应声明为Optional[T](需提前从typing导入Optional和TypeVar)。

修改后的send方法代码:

from typing import TypeVar, Optional

T = TypeVar("T")

def send(self, operation: ServerOperation[T]) -> Optional[T]:
    command = operation.get_command(self.__request_executor.conventions)
    self.__request_executor.execute_command(command)
    return command.result

关键说明

  • 原代码中isinstance(operation, ServerOperation)的判断是冗余的,因为参数类型已经限定为ServerOperation[T],可以直接移除。
  • 通过泛型绑定,类型检查器能自动推断出command是RavenCommand[T]类型,因此command.result的类型与返回类型Optional[T]完全匹配。

内容的提问来源于stack exchange,提问作者poisson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:54:16