【发布时间】:2021-12-15 18:31:32
【问题描述】:
我想用python制作实体组件系统(ECS)。
我让Entity 上课:
from typing import Optional, TypeVar, Type
T = TypeVar('T')
class Entity:
def __init__(self):
self.components = []
def add_component(self, c):
self.components.append(c)
def get_first_component(self, Type: Type[T]) -> Optional[T]:
for c in self.components:
if isinstance(c, Type):
return c
def get_first_components(self, *Types):
res = []
for Type in Types:
res.append(self.get_first_component(Type))
return res
get_first_component 的类型提示很简单,但我不明白如何为get_first_components 函数进行类型提示。该函数给出类型列表并返回这些类型的对象列表。
例子:
e.get_first_components(Position, Health) # returns [Position(2, 2), Health(10, 10)]
我是这样看的:
A = TypeVar('A')
B = TypeVar('B')
def f(Types: [Type[A], Type[B], ...]) -> [A, B, ...]:
# some code ...
对不起,我的英语不好:(
需要在系统中进行类型提示:
class MoveSystem(System):
def __init__(self) -> None:
pass
def run_for_entity(self, e: Entity):
pos, m2 = e.get_first_components(Pos2, Move2)
if m2.active: # <- no type hinting after typing "m2."
pos.x += m2.dx
pos.y += m2.dy
m2.active = False
【问题讨论】:
-
*Types: Type[T]?而返回类型只是-> List[Optional[Type[T]]] -
@juanpa.arrivillaga:我认为返回值是
List[Optional[T]],因为列表中的值是参数中给出的类型的实例。我也不确定这是否可行,因为正在寻找的类型可能没有共同的基类(object除外),所以T的描述性不会很强。
标签: python python-3.x game-engine type-hinting