函数签名中出现“TypeError:‘type’对象不可下标”
- 2025-03-12 08:52:00
- admin 原创
- 37
问题描述:
为什么我运行此代码时会收到此错误?
Traceback (most recent call last):
File "main.py", line 13, in <module>
def twoSum(self, nums: list[int], target: int) -> list[int]:
TypeError: 'type' object is not subscriptable
nums = [4,5,6,7,8,9]
target = 13
def twoSum(self, nums: list[int], target: int) -> list[int]:
dictionary = {}
answer = []
for i in range(len(nums)):
secondNumber = target-nums[i]
if(secondNumber in dictionary.keys()):
secondIndex = nums.index(secondNumber)
if(i != secondIndex):
return sorted([i, secondIndex])
dictionary.update({nums[i]: i})
print(twoSum(nums, target))
解决方案 1:
以下答案仅适用于 Python < 3.9
表达式list[int]
试图对对象 进行下标list
,该对象是一个类。类对象属于其元类的类型,type
在本例中为 。由于type
未定义__getitem__
方法,因此您无法执行list[...]
。
为了正确执行此操作,您需要导入typing.List
并使用它,而不是在类型提示中使用内置功能list
:
from typing import List
...
def twoSum(self, nums: List[int], target: int) -> List[int]:
如果您想避免额外的导入,您可以简化类型提示以排除泛型:
def twoSum(self, nums: list, target: int) -> list:
或者,你可以完全摆脱类型提示:
def twoSum(self, nums, target):
解决方案 2:
将@Nerxis 的评论转化为答案。
对于 Python 3.7 和 3.8,添加:
from __future__ import annotations
作为您第一次导入到模块中。
List
虽然使用代替的答案list
是可以的,但是当您需要执行 时它不会帮助您pd.Series[np.int64]
。请改用上面的方法。
解决方案 3:
概括
代码中说的部分-> list[int]
是函数返回类型的类型注释。这是一种特殊的符号,第三方工具可以使用它来对代码进行一些基本的静态类型检查。就 Python 本身而言,它对代码的唯一影响是向函数添加一些元数据:
>>> def example() -> list[int]:
... pass
...
>>> 'return' in example.__annotations__
True
Python 本身不会进行任何类型检查:
>>> type(example()) # definitely did not give a list of integers!
<class 'NoneType'>
类似地,部分是 的参数: list[int]
的类型注释。nums
`twoSum`
根据 Python 版本的不同,此特定的注释可能不被接受。
Python 3.9 及更高版本
该错误无法重现。-> list[int]
声明该函数旨在返回包含所有整数值的列表,并: list[int]
声明应为传入另一个这样的列表nums
。这些提示允许第三方工具(如 MyPy)在编译或运行代码之前查找问题。
Python 3.7 或 3.8
此注释不按原样接受。有两种解决方法:
使用导入来访问PEP 563
__future__
中描述的“推迟评估注释”行为:
# At the top of the code, along with the other `import`s
from __future__ import annotations
使用标准库模块中定义的相应类
typing
:
# At the top of the code
from typing import List
# when annotating the function
def twoSum(self, nums: List[int], target: int) -> List[int]:
注意 中的大写List
L。
Python 3.5 和 3.6
__future__
不支持该注释。请使用typing
模块。
Python 3.4 及更低版本
根本不支持类型注释。只需将其删除即可:
def twoSum(self, nums, target):
再次提醒,请记住Python 本身不会对注释做任何有意义的事情。它们不会导致代码因无效参数而引发异常,将它们转换为正确的类型,或执行其他任何类似操作。它们仅适用于第三方工具,并且完全是可选的,除非其他第三方工具强制使用它们。
解决方案 4:
上面“疯狂物理学家”给出的答案有效,但是这个关于 3.9 新功能的页面表明“list[int]”也应该有效。
https://docs.python.org/3/whatsnew/3.9.html
但是对我来说不起作用。也许mypy还不支持3.9的这个功能。
解决方案 5:
我在通过 执行 Python 脚本时遇到了类似的问题python -m <package>.<module>
。我可以通过从 PowerShell 切换到 cmd 来避免这个问题。这可能是因为 PowerShell 使用的 Python 版本与我的 cmd 不同,我无法检查。(Windows 10 + Python 3.10)