Wie schreibe ich eine generische Unterklasse richtig ein?

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Wie schreibe ich eine generische Unterklasse richtig ein?

by Anonymous » 20 Mar 2025, 15:09

Hier ist ein Beispielcode: < /p>
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]): ...
Mein Problem ist, dass ich den Typ t für myObjmgr angeben muss (generisches [Tobj, t]) , um den ID -Typ des zugrunde liegenden Objekts anzugeben. Gibt es eine Möglichkeit, t aus Tobj [t] ?
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]): ...

Top