小编Ice*_*ube的帖子

返回类实例的抽象类方法的键入提示

我在以下代码中遇到类型检查器错误,我很想了解如何解决该错误。

下面的基类有一个抽象类方法,我希望从它继承的每个子类都将实现一个decode返回子类实例的函数。

from abc import ABC, abstractmethod
from typing import TypeVar


TMetricBase = TypeVar("TMetricBase", bound="MetricBase")


class MetricBase(ABC):
    @abstractmethod
    def add(self, element: str) -> None:
        pass  # pragma: no cover

    @classmethod
    @abstractmethod
    def decode(cls, json_str: str) -> TMetricBase:
        pass  # pragma: no cover


Run Code Online (Sandbox Code Playgroud)

子类如下所示

import json
from typing import Any, Callable, List, Mapping, Optional
from something import MetricBase, TMetricBase


class DiscreteHistogramMetric(MetricBase):
    def __init__(self, histogram: Optional[Mapping[str, int]]) -> None:
        super().__init__()
        self._histogram = dict(histogram) if histogram else {}

    def add(self, element: …
Run Code Online (Sandbox Code Playgroud)

python type-hinting python-3.x python-typing

8
推荐指数
2
解决办法
4299
查看次数

标签 统计

python ×1

python-3.x ×1

python-typing ×1

type-hinting ×1