[Python] How do I get the type that was passed into a generic class's constructor? [duplicate]

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    Consider this:

    from typing import Generic, Optional, TypeVar, cast

    T = TypeVar("T")

    class Test(Generic[T]):
    name: str
    value: Optional[T] = None

    def __init__(
    self,
    name: str,
    value: Optional[T] = None,
    ):
    self.name = name
    self.value = value

    test_int = Test[int](name="test")
    test_str = Test[str](name="test")


    What property do I use to see that test_int was instantiated as int and test_str was instantiated as str? I cannot figure out how to get this information.

    Continue reading...

Compartilhe esta Página