Generics/templates in python?

前端 未结 10 1471
深忆病人
深忆病人 2020-12-22 19:16

How does python handle generic/template type scenarios? Say I want to create an external file \"BinaryTree.py\" and have it handle binary trees, but for any data type.

10条回答
  •  离开以前
    2020-12-22 19:44

    The other answers are totally fine:

    • One does not need a special syntax to support generics in Python
    • Python uses duck typing as pointed out by André.

    However, if you still want a typed variant, there is a built-in solution since Python 3.5.

    Generic classes:

    from typing import TypeVar, Generic
    
    T = TypeVar('T')
    
    class Stack(Generic[T]):
        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
    
    # Construct an empty Stack[int] instance
    stack = Stack[int]()
    stack.push(2)
    stack.pop()
    stack.push('x')        # Type error
    

    Generic functions:

    from typing import TypeVar, Sequence
    
    T = TypeVar('T')      # Declare type variable
    
    def first(seq: Sequence[T]) -> T:
        return seq[0]
    
    def last(seq: Sequence[T]) -> T:
        return seq[-1]
    
    
    n = first([1, 2, 3])  # n has type int.
    

    Reference: mypy documentation about generics.

提交回复
热议问题