CKTIS / Python
typing.Generic
Základ Generic[T] deklaruje triedu s vopred vytvorenou typovou premennou T.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
class Box(Generic[T]): ...Základ Generic[T] deklaruje triedu s vopred vytvorenou typovou premennou T.
Moderný zápis class Box[T] tiež zavádza typový parameter.
Špecializácia Box[int] uchová argument na kontrolu metadát, ale hodnotu pri konštrukcii neoverí a prijme reťazec.
Príklady
from typing import Generic, TypeVar, get_args, get_origin
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
spec = Box[int]
print(get_origin(spec) is Box, get_args(spec) == (int,))
box = spec("note")
print(type(box) is Box, box.value)
Výsledok
True True True note
Špecializácia Box[int] uchová argument na kontrolu metadát, ale hodnotu pri konštrukcii neoverí a prijme reťazec.