【发布时间】:2019-08-16 03:43:29
【问题描述】:
作为一名 C++ 程序员,以下代码对我来说似乎很自然,但它不会运行:
from typing import TypeVar, Generic, List, NewType
TPopMember = TypeVar('TPopMember')
Population = NewType('Population', List[TPopMember])
class EvolutionaryAlgorithm(Generic[TPopMember]):
def __init__(self, populationSize: int) -> None:
# The following raises TypeError: 'TypeVar' object is not callable
self.__population = Population([TPopMember() for _ in range(populationSize)])
显然 Python 无法实例化实际上是 TypeVar 的类(TPopMember)。我只是想创建一个带有几个默认初始化的列表(人口)(你在 Python 中怎么说?)TPopMembers。我该怎么办?
我正在使用 Python 3.7.2。
【问题讨论】:
-
请记住,这些只是提示。我建议创建一个新的
classTPopMember -
您可以通过要求将
TPopMember工厂传递给EvolutionaryAlgorithm。
标签: python python-3.x type-hinting