【发布时间】:2021-09-08 03:58:41
【问题描述】:
有如下功能:
import pdfplumber
from pdfplumber.page import Page
def searchFromFile(path:str,keyword:str) -> list[Page]:
with pdfplumber.open(path) as pdf:
result = [Page]
for page in pdf.pages:
pageText = page.extract_text()
if pageText != None and keyword in pageText:
result.append(page)
return result
为了更准确,我将返回的list定义为Java中的泛型类型,即list[Page],但它不起作用并出现错误:
TypeError: 'type' object is not subscriptable
问题:是否可以将返回的list 定义为泛型类型?
【问题讨论】:
-
应该可以。你得到了什么错误?您是否已经定义了
Page类? -
@Barmar 我粘贴了整个函数,所以
Page来自pdfplumber -
您需要 Python 3.9 或更高版本才能使用
list作为泛型类型。 -
那就不要使用
list[Page];使用typing.List[Page]。
标签: python python-3.x generic-type-argument