typing 是在 python 3.5 才有的模块
Python 类型提示:https://cloud.tencent.com/developer/article/1864619
前两行小写的不需要 import,后面三行都需要通过 typing 模块 import 哦
# name 参数类型为 str
def greeting(name: str) :
return "hello"
# 多个参数,参数类型均不同
def add(a: int, string: str, f: float, b: bool or str):
print(a, string, f, b)
bool or str:代表参数 b 可以是布尔类型,也可以是字符串
# 函数返回值指定为字符串
def greeting(name: str) -> str:
return "hello"
from typing import Tuple, List, Dict
# 返回一个 Tuple 类型的数据,第一个元素是 List,第二个元素是 Tuple,第三个元素是 Dict,第四个元素可以是字符串或布尔
def add(a: int, string: str, f: float, b: bool or str) -> Tuple[List, Tuple, Dict, str or bool]:
list1 = list(range(a))
tup = (string, string, string)
d = {"a": f}
bl = b
return list1, tup, d, bl
# 不 warn 的调用写法
print(add(1, "2", 123, True))
# 输出结果
([0], ('2', '2', '2'), {'a': 123}, True)
能大概猜到,它们底层跟 list、set、dict 有关系
跟其他三个不太一样,但也是跟 tuple 有关系
那指定类型的时候用 list、set、dict、tuple 可不可以呢?
可以是可以,但是不能指定里面元素数据类型
def test(a: list, b: dict, c: set, d: tuple):
print(a, b, c, d)
a: List[int, str] = [1, "2"]
b: Set[int, str] = {1, 2, 3}
IDE 不会报错,但运行时会报错
Traceback (most recent call last):
File "/Users/polo/Documents/pylearn/第二章:基础/13_typing.py", line 36, in <module>
a: List[int, str] = [1, "2"]
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/typing.py", line 261, in inner
return func(*args, **kwds)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/typing.py", line 683, in __getitem__
_check_generic(self, params)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/typing.py", line 215, in _check_generic
raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
TypeError: Too many parameters for typing.List; actual 2, expected 1
大致意思就是:List 传了太多参数,期望 1 个,实际 2 个
d: Tuple[int, str] = (1, "2")
print(d)
# 输出结果
(1, '2')
是不会报错的
只写一个 int,赋值两个 int 元素会报 warning
如果 TupleT 指定类型数量和赋值的元素数量不一致呢?
d: Tuple[int, str] = (1, "2", "2")
不会报错,但是也会有 warning
TupleT 指定一个类型的时候,仅针对同一个索引下的元素类型
d: Tuple[int, ...] = (1, 2, 3)
d: Tuple[Dict[str, str], ...] = ({"name": "poloyy"}, {"age": "33"})
指定一个类型后,在后面加个 ... 就行
https://www.cnblogs.com/poloyy/p/15153883.html
https://www.cnblogs.com/poloyy/p/15153886.html
https://cloud.tencent.com/developer/article/1866297
https://cloud.tencent.com/developer/article/1866293