Skip to content

Python 类型标注 ​

构建习惯 ​

使用类型提示

python
name: str = "John"
age: int = 25

def greet(name: str) -> str:
    return "Hello, " + name

3.6引入泛型(Generic) 使用泛型可以为容器类(如列表、字典等)指定其中元素的类型。例如: '容器元素的预期类型'。和type hint 一样,并不强制

python
from typing import TypeVar

T = TypeVar('T')


def func(value: T) -> T:
    return value

result = func(1)
result = func(1.0)  #result 类型 float
python
numbers : list[int] = [1, 5, 3, 2, 7, 8, 10, 0]
a = sorted(numbers)
b = numbers.sort()  #in-place 返回None,改变了numbers, b=None
print(a)
print(b)
print(numbers)
'''
[0, 1, 2, 3, 5, 7, 8, 10]
None
[0, 1, 2, 3, 5, 7, 8, 10]
'''

执行函数, 无返回值-, 提示None 即返回None '在 Python 中 (以及在标准库的所有代码中) 会改变原对象的方法将返回 None() '

python
def Myswap(a:int, b:int) -> None:
    a, b = b, a
    print(a, b) 
x,y =1,7
Myswap(x, y)
print(x,y)
'''
7 1
1 7
'''
#测试
def Myswap(a:int, b:int) -> None:
    a, b = b, a
    print(a, b) 
Sw=Myswap(100, 2)
print(Sw)
'''

2 100
None
'''

None 用法

python
def Add_dict(number:int = 0,target:dict = None) -> dict:
	if target == None :
		target ={}
		...
	for index,(key,value) in enumerate(target.items()):
	
		target[key]= value + number
	return target
print(Add_dict(3,{'a':1,'b':2,'c':3}))
'''
{'a': 4, 'b': 5, 'c': 6}
'''

基于 VitePress 构建 · 托管于 Cloudflare Pages