Python3+ 类定义中的泛型可变类型

问题描述 投票:0回答:1

有一段时间没用过Python了。我正在实现一个简单的堆栈:

class Stack:
    def __init__(self):
        self.stack = []

    def push(self, val) -> None:
        self.stack.append(val)

    def pop(self) -> int:
        return self.stack.pop()

我的问题是关于这一行 -

def pop(self) -> int
,我将返回值硬编码为
int
。如果我想让我的
Stack
适用于任何类型的列表
list<T>
怎么办?我想
typing.TypeVar
在这里会有用吗?基本上给出
self.stack: list<T>
然后
pop(self) -> T
。所以当我
def __init__(self)
我需要更新 Stack 以知道它的元素是
T
?

我希望我已经足够清楚地表达了这一点。这显然是一个玩具示例,但我正在尝试了解有关类型化 Python 3 的更多信息。

注意 这个数据结构一开始可能是非 pythonic 的,因为我认为列表不应该被键入。欢迎任何关于为什么会这样以及如何思考它的评论或进一步阅读!

python types variadic
1个回答
2
投票

你想要

Generic
TypeVar

from typing import TypeVar, Generic

T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self):
        self.stack = []

    def push(self, val: T) -> None:
        self.stack.append(val)

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

s = Stack[int]()
x = s.pop()  # Knows x is an 'int'

s.push("hello")  # Expected type 'int' (matched generic type 'T'), got 'str' instead
© www.soinside.com 2019 - 2024. All rights reserved.