如何向工厂方法添加提示?

How to add hint to a factory method?

我正在寻找一种方法来注释 return 类型的工厂函数。

它 return 是 'AlgorithmBase' 的随机 child。

class AlgorithmFactory:
    _algorithm_types = AlgorithmBase.__subclasses__()

    def select_random_algorithm(self) -> AlgorithmBase:
        # Select random algorithm
        algorithm_class = self._random_generator.choice(AlgorithmFactory._algorithm_types)
        algorithm = algorithm_class()
        return algorithm

我从 mypy 中得到错误:

我得到的错误是:

Cannot instantiate abstract class 'AlgorithmBase' with abstract attributes 'get_constraints' and 'satisfy_constraints'

这段代码没有办法实例化class 'AlgorithmBase',如何让mypy看懂?

我想避免在 return 类型中使用 'Union' 指定实际的 sub-classes。有什么建议吗?

这里的问题不是 return 类型,而是“_algorithm_types”。 mypy 无法理解它是什么类型,因此它假定它类似于 return 类型并出错。

以下代码解决了这个问题:

_algorithm_types: List[Type[AlgorithmBase]] = AlgorithmBase.__subclasses__()

据我所知这应该可行,但您的 AlgorithmBase 子类中的一个或多个似乎没有实现这两个抽象方法。

运行

的 MyPy
import abc

class AlgorithmBase(abc.ABC):
    @abc.abstractmethod
    def get_constraints(self):
        raise NotImplementedError

    @abc.abstractmethod
    def satisfy_constraints(self):
        raise NotImplementedError


class SomeAlgorithm(AlgorithmBase):
    pass


class AlgorithmFactory:
    def get(self) -> AlgorithmBase:
        algorithm = SomeAlgorithm()
        return algorithm

产生与您相同的错误,并且在实施方法后运行时没有任何错误。

import abc

class AlgorithmBase(abc.ABC):
    @abc.abstractmethod
    def get_constraints(self):
        raise NotImplementedError

    @abc.abstractmethod
    def satisfy_constraints(self):
        raise NotImplementedError


class SomeAlgorithm(AlgorithmBase):
    def get_constraints(self):
        pass

    def satisfy_constraints(self):
        pass


class AlgorithmFactory:
    def get(self) -> AlgorithmBase:
        algorithm = SomeAlgorithm()
        return algorithm