Ich habe mein zugrunde liegendes generisches Objekt.
Code: Select all
T = TypeVar("T", str, int, bytes)
class MyObj(Generic[T]):
id: T
< /code>
und einige Implementierungen < /p>
class MyObjImplInt(MyObj[int]): ...
class MyObjImplStr(MyObj[str]): ...
obj_int = MyObjImplInt()
type(obj_int.id) # int
obj_str = MyObjImplStr()
type(obj_str.id) # str
< /code>
Jetzt habe ich einen Manager für diese Objekte erstellt.TObj = TypeVar("TObj", bound=MyObj)
class MyObjMgr(Generic[TObj, T]):
objs: list[TObj]
def __init__(self, objs: list[TObj]):
self.objs = objs
def get_by_id(self, obj_id: T):
return [e for e in self.objs if e.id == obj_id]
class MyObjMgrInts(MyObjMgr[MyObjImplInt, int]): ...
class MyObjMgrStrs(MyObjMgr[MyObjImplStr, str]): ...
i.e zu schließen. Schreiben Sie einfach Folgend
Code: Select all
class MyObjMgr2(Generic[TObj]):
objs: list[TObj]
def __init__(self, objs: list[TObj]):
self.objs = objs
def get_by_id(self, obj_id: T@TObj): # err here
return [e for e in self.objs if e.id == obj_id]
class MyObjMgr2Ints(MyObjMgr2[MyObjImplInt]): ...