示例工程 11-protocols-generics-overloads
11-protocols-generics-overloads/02-generic-preserves-type/generic_preserves_type.py
"""演示泛型在静态检查中保留元素类型,在运行时被擦除。"""
from __future__ import annotations
from collections.abc import Sequence
from typing import Any, Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def get(self) -> T:
return self.value
def first(items: Sequence[T]) -> T:
return items[0]
def first_any(items: Sequence[Any]) -> Any:
return items[0]
def main() -> None:
numbers = [10, 20, 30]
value = first(numbers)
print(f"first: {value!r}")
print(f"first type: {type(value).__name__}")
any_value = first_any(numbers)
print(f"any: {any_value!r}")
print(f"generic repr: {Box[int]!r}")
typed = Box[int](42)
print(f"instance class: {type(typed).__name__}")
print(f"orig class: {getattr(typed, '__orig_class__', None)!r}")
plain = Box(7)
print(f"plain has orig: {hasattr(plain, '__orig_class__')}")
if __name__ == "__main__":
main()