如何向工厂方法添加提示? [英] How to add hint to a factory method?
问题描述
我正在寻找一种方法来注释工厂函数的返回类型.
I'm looking for a way to annotate return type of a factory function.
它返回'AlgorithmBase'的随机子节点.
It returns random child of '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 得到错误:
I get error from mypy:
我得到的错误是:
Cannot instantiate abstract class 'AlgorithmBase' with abstract attributes 'get_constraints' and 'satisfy_constraints'
这段代码中没有办法实例化'AlgorithmBase'类,如何让mypy理解呢?
There is no way to instantiate class 'AlgorithmBase' in this code, how to make mypy understand it?
我想避免在返回类型中指定带有Union"的实际子类.有什么建议吗?
I want to avoid specifying actual sub-classes with 'Union' in return type. Any suggestions?
推荐答案
这里的问题不是返回类型,而是_algorithm_types".mypy 无法理解它是什么类型,所以它假设它像返回类型并出错.
The problem here wasn't return type, but '_algorithm_types'. mypy has no way to understand what type it is, so it assumed that it is like return type and got error.
以下代码解决了这个问题:
The following code fix the issue:
_algorithm_types: List[Type[AlgorithmBase]] = AlgorithmBase.__subclasses__()
这篇关于如何向工厂方法添加提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!