CKTIS / Python
typing.Generic
Základ Generic[T] deklaruje třídu s předem vytvořenou typovou proměnnou T.
Verze: Python 3.14; repository image, production runtime not attested
Syntaxe
class Box(Generic[T]): ...Základ Generic[T] deklaruje třídu s předem vytvořenou typovou proměnnou T.
Moderní zápis class Box[T] rovněž zavádí typový parametr.
Specializace Box[int] uchová argument pro inspekci, ale hodnotu při konstrukci neověří a přijme řetězec.
Pří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ýsledek
True True True note
Specializace Box[int] uchová argument pro inspekci, ale hodnotu při konstrukci neověří a přijme řetězec.