Python 类型注解语法
类型注解标注函数参数和返回值类型,增强代码可读性和安全性。
函数类型注解
Python
# 参数类型注解
def greet(name: str) -> str:
return "Hello, " + name
# 多参数注解
def add(a: int, b: int) -> int:
return a + b
# 无返回值
def log(message: str) -> None:
print(message)
# 无参数无返回值
def reset() -> None:
pass
默认参数注解
Python
# 默认参数类型注解
def greet(name: str = "World") -> str:
return "Hello, " + name
# 多个默认参数
def create_user(
name: str,
age: int = 0,
active: bool = True
) -> dict:
return {'name': name, 'age': age, 'active': active}
可变参数注解
Python
from typing import List
# *args 注解
def sum_all(*args: int) -> int:
return sum(args)
# **kwargs 注解
def create_dict(**kwargs: str) -> dict:
return kwargs
# 混合使用
def process(
name: str,
*args: int,
**kwargs: str
) -> List[int]:
return list(args)
复杂返回类型
Python
from typing import List, Dict, Tuple, Optional
# 返回列表
def get_names() -> List[str]:
return ['Alice', 'Bob']
# 返回字典
def get_scores() -> Dict[str, int]:
return {'Alice': 90}
# 返回元组
def get_point() -> Tuple[int, int]:
return (10, 20)
# 返回可选值
def find_user(id: int) -> Optional[str]:
if id > 0:
return 'Alice'
return None
类方法注解
Python
class User:
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
def get_info(self) -> str:
return f"{self.name}, {self.age}"
def update(self, new_name: str) -> None:
self.name = new_name
# 类方法
@classmethod
def create(cls, name: str) -> 'User':
return cls(name, 0)
# 静态方法
@staticmethod
def validate_age(age: int) -> bool:
return age >= 0
self 类型注解
Python
from typing import TypeVar
T = TypeVar('T', bound='Person')
class Person:
def __init__(self, name: str) -> None:
self.name = name
def copy(self: T) -> T:
return type(self)(self.name)
class Student(Person):
pass
# Student.copy() 返回 Student 类型
Generator 注解
Python
from typing import Generator
def generate_numbers(n: int) -> Generator[int, None, None]:
for i in range(n):
yield i
# Generator[YieldType, SendType, ReturnType]
def interactive_gen() -> Generator[int, int, str]:
received = yield 1
yield received + 1
return "done"
Async 函数注解
Python
from typing import Coroutine
async def fetch_data(url: str) -> str:
return "data"
# Coroutine[YieldType, SendType, ReturnType]
async def async_gen() -> Coroutine[None, None, int]:
return 42
类型注解位置
Python
# 参数:冒号后
def func(param: type) -> return_type:
pass
# 变量:冒号后(可选)
x: int = 10
name: str = "Alice"
# 类属性
class Config:
timeout: int = 30
debug: bool = False
注解 vs 文档字符串
Python
# 类型注解:简洁,机器可读
def add(a: int, b: int) -> int:
return a + b
# 文档字符串:详细,人类可读
def add(a: int, b: int) -> int:
"
计算两个整数的和。
Args:
a: 第一个整数
b: 第二个整数
Returns:
两数之和
"
return a + b
要点总结
- 参数注解:
param: type - 返回值注解:
-> return_type - 无返回值使用
-> None - 可变参数注解整体类型
- 类方法 self 不需要注解
- 使用
'ClassName'前向引用 - Generator 注解三个类型参数
- 类型注解 + 文档字符串最佳组合
- 注解提高 IDE 智能提示和静态检查
📝 发现内容有误?点击此处直接编辑