类型。">
在变量名后面加冒号 : 类型,在函数后面加箭头 -> 类型。
# 凡人写法
def add(x, y):
return x + y
# 天眼写法
def add(x: int, y: int) -> int:
return x + y
这样,IDE (剑灵) 就能提示你:这里只能传数字!
如果是个纳戒 (List),里面装的是数字呢?
from typing import List, Dict, Optional
# 一个装满数字的纳戒
scores: List[int] = [90, 80, 100]
# 一个通讯录
contacts: Dict[str, str] = {"师姐": "1314"}
# 可能会空的宝箱 (Optional)
treasure: Optional[str] = None
新版 Python 更加简洁,不需要从 typing 召唤太多东西。
# 现在的写法 (小写即可)
def process_items(items: list[str]):
for item in items:
print(item.upper())
任务:给 def greet(name): return "Hello " + name 加上类型注解。
(name 是 str,返回值也是 str)