File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -583,6 +583,7 @@ argument(s) is substituted. Otherwise, ``Any`` is assumed. Example::
583583 class Node(Generic[T]):
584584 def __init__(self, label: T = None) -> None:
585585 ...
586+ x: None # Type: T
586587
587588 x = Node('') # Inferred type is Node[str]
588589 y = Node(0) # Inferred type is Node[int]
@@ -610,6 +611,21 @@ the runtime class of the objects created by instantiating them doesn't
610611record the distinction. This behavior is called "type erasure"; it is
611612common practice in languages with generics (e.g. Java, TypeScript).
612613
614+ Class attribute of a generic class can be looked up only through the instance
615+ of the class; any attempt to use generic classes (parametrized or not) to
616+ access attributes will result in both type check failure and runtime error::
617+
618+ # (continued from previous example)
619+ Node[int].x = 1 # Error
620+ Node[int].x # Error
621+ Node.x = 1 # Error
622+ Node.x # Error
623+ type(p).x # Error
624+ p.x # Ok
625+ Node[int]().x # Ok
626+
627+ In addition, ``ClassVar`` cannot be parametrized.
628+
613629Generic versions of abstract collections like ``Mapping`` or ``Sequence``
614630and generic versions of built-in classes -- ``List``, ``Dict``, ``Set``,
615631and ``FrozenSet`` -- cannot be instantiated. However, concrete user-defined
@@ -2439,7 +2455,7 @@ Copyright
24392455This document has been placed in the public domain.
24402456
24412457
2442-
2458+
24432459..
24442460 Local Variables:
24452461 mode: indented-text
You can’t perform that action at this time.
0 commit comments