本人python新手, 在翻閱pep484, 以及mypy文檔的時(shí)候有遇到了一點(diǎn)不懂的地方, 如下:# 文檔實(shí)例如下: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然后文檔下面有這樣一段話:The Stack class can be used to represent a stack of any type: Stack[int], Stack[Tuple[int, str]], etc然后給出了一段實(shí)例用法:# Construct an empty Stack[int] instancestack = Stack[int]()
stack.push(2)
stack.pop()
stack.push('x') # Type error我個(gè)人的理解是:T表示任意類型Stack[int]表示Stack只能存儲(chǔ)int類型, 所以下面?zhèn)魅肓艘粋€(gè)字符串就報(bào)錯(cuò)疑惑是:不知道上面的理解對(duì)不對(duì)如果我在一開始就確定好堆里面的數(shù)據(jù)類型就行了為什么要?jiǎng)?chuàng)造一個(gè)泛型?泛型在python中有沒有什么使用場(chǎng)景, 本人沒有接觸過java之類的語言, 因此覺得就看看例子感覺特別抽象, 也不知道在上面場(chǎng)景下如何使用.本人剛剛接觸python, 若有理解錯(cuò)誤的地方還請(qǐng)多多包涵, 望有前輩能夠解惑!
python 泛型注釋的不理解?
長(zhǎng)風(fēng)秋雁
2018-08-26 15:05:28