1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] how to define python generic classes [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    I have a class:

    T = TypeVar('T')


    class Stack(Generic[T]):
    def __init__(self) -> None:
    self.items: list[T] = []

    def push(self, item: T) -> None:
    self.items.append(item)

    def pop(self) -> T:
    return self.items.pop()

    def empty(self) -> bool:
    return not self.items


    but I can also do:

    T = TypeVar('T')


    class Stack:
    def __init__(self) -> None:
    # Create an empty list with items of type T
    self.items: list[T] = []

    def push(self, item: T) -> None:
    self.items.append(item)

    def pop(self) -> T:
    return self.items.pop()

    def empty(self) -> bool:
    return not self.items

    1. what is the difference between these two samples?
    2. which on should I use?

    I tried running both, and both worked.

    Continue reading...

Compartilhe esta Página