我在下面的代码中得到了类型检查器错误,我希望能够理解如何解决这个错误。
以下基类有一个抽象类方法,我希望每个继承它的子类都实现一个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
子类如下所示
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: str) -> None:
self._histogram[element] = self._histogram.get(element, 0) + 1
@classmethod
def decode(cls, json_str: str) -> "DiscreteHistogramMetric":
json_obj = json.loads(json_str)
histogram_map = json_obj["DiscreteHistogramMetric"]
return cls(histogram=histogram_map)
我遇到了以下错误:
error: Return type of "decode" incompatible with supertype "MetricBase"
当将decode
的返回类型更改为TMetricBase
时,我会收到以下错误:
error: Incompatible return value type (got "DiscreteHistogramMetric", expected "TMetricBase")