12.python-类型提示
python 类型提示
它允许开发者在代码中显式地声明变量、函数、方法等的类型信息。这种类型声明不会影响 Python 解释器的运行,它可以帮助开发人员在编写代码时更好地理解代码中的数据类型,从而提高代码的可读性和可维护性。
基本类型
# 直接定义
age: int = 1
# 声明后定义
num: float
num = 2.0
name:str = "beike"
def printname(name: str) -> str:
return f"Hello, {name}!"
def is_even(x: int) -> bool:
return x % 2 == 0
res=printname(name)
print(res)
嵌套类型
使用标准库 typing 标记复合类型
from typing import List, Tuple, Dict, Set
my_list: List[int] = [1, 2, 3, 4]
my_tuple: Tuple[int, str, bool] = (1, "hello", True)
my_dict: Dict[str, int] = {"apple": 1, "banana": 2, "orange": 3}
my_set: Set[float] = {1.0, 2.0, 3.0}
复合类型
Union类型用于表示多种类型中的一种,Optional类型用于表示可选类型,Sequence 序列类型
from typing import Union
def func(x: Union[int, str]) -> None:
pass
from typing import Optional, Union
def func(x: Optional[Union[int, str]]) -> None:
pass
Sequence 类型的对象是可以被索引的任何东西:列表、元组、字符串、对象列表、元组列表的元组等。
def test(a: Sequence):
print(a[0])
...
Generator-Iterator
from typing import Generator
def even_numbers(n: int) -> Generator[int, None, None]:
for i in range(n):
if i % 2 == 0:
yield i
from typing import Iterator
class MyIterator:
def __init__(self):
self.current: int = 0
self.max: int = 5
def __iter__(self) -> Iterator[int]:
return self
def __next__(self) -> int:
if self.current >= self.max:
raise StopIteration
else:
self.current += 1
return self.current
Callable
from typing import Callable
def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
def add(a: int, b: int) -> int:
return a + b
result = apply(add, 3, 4)
print(result) # 输出7
自定义类型
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def say_hello(person: Person) -> str:
return f"Hello, {person.name}!"
其他类型NamedTuple
from typing import NamedTuple
from collections import namedtuple
Employee = namedtuple('Employee', ["x","y"])
em = Employee(x=1, y='x')
print(em.x,em.y)
Point = NamedTuple('Point', [('x', int),
('y', str)])
p = Point(x=1, y='x')
print(p.x,p.y)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?