环境:python3
将leetcode上的代码复制到本地,运行报错:NameError: name 'List' is not defined
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
pass
在头部导typing
模块。
from typing import List
python是一门弱类型的语言,使用过程不用过多关注变量的类型,但是同时也带来了可读性问题,有时候自己都不知道传入的是什么参数。因此在python3.5之后,引入了typing模块。
函数接受并返回一个字符串,使用示例:
import typing
def greeting(name: str) -> str:
return 'Hello ' + name
在函数 greeting 中,参数 name 预期是 str 类型,并且返回 str 类型。子类型允许作为参数。
from typing import List
def func(num:int, string:str) -> List[int or str]:
/1. import typing
后直接可用的:
/2. 需要from typing import ...
的:
def foo_func(arg: Optional[int]):
注意
:迭代器中的元素可能是多种类型,使用or或union操作符
本文系转 NameError: name ‘List’ is not defined ,并根据笔者实测做了一些更正。
其他参考:https://www.cnblogs.com/poloyy/p/15170297.html
⬇️ 下面是个csdn牛皮癣广告。有人知道怎么去掉它吗?