我正在寻找一种注释工厂函数的返回类型的方法。
它返回'AlgorithmBase'的随机子级。
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'
在此代码中无法实例化类'AlgorithmBase',如何使mypy理解它?
我想避免在返回类型中指定带有'Union'的实际子类。有什么建议吗?
这里的问题不是返回类型,而是'_algorithm_types'。 mypy无法理解它是什么类型,因此它假定它就像返回类型一样,并出现错误。
以下代码解决了该问题:
_algorithm_types: List[Type[AlgorithmBase]] = AlgorithmBase.__subclasses__()
据我所知这应该可行,但是您的一个或多个AlgorithmBase
子类似乎没有实现这两个抽象方法。
运行MyPy for
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