Wie schreibe ich eine generische Unterklasse richtig ein?Python

Python-Programme
Anonymous
 Wie schreibe ich eine generische Unterklasse richtig ein?

Post by Anonymous »

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]): ...

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post