全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 6 分钟 ✍️ juanwangdev

Python 基本类型注解

基本类型注解使用内置类型标注变量,提高代码可读性。

内置类型注解

Python
# 数值类型
count: int = 10
price: float = 99.99
ratio: float = 0.5

# 字符串类型
name: str = "Alice"
message: str = "Hello"

# 布尔类型
active: bool = True
enabled: bool = False

# 空值
result: None = None

变量注解语法

Python
# 变量注解
variable: type = value

# 注解不初始化(需要后续赋值)
x: int  # 仅注解,不赋值
x = 10  # 后续赋值

# 类属性注解
class Config:
    name: str
    timeout: int = 30

注解与类型转换

Python
# 注解不强制类型转换
x: int = "10"  # 注解错误但运行正常

# 正确使用
x: int = int("10")

# 类型注解是提示,不影响运行
def process(value: int):
    print(value)

process("string")  # 运行正常,类型检查报错

多变量注解

Python
# 多变量同时注解
a: int
b: int
c: int

a, b, c = 1, 2, 3

# 列表解包注解
x: int
y: int
z: int
x, y, z = [1, 2, 3]

函数内变量注解

Python
def calculate(price: float, quantity: int) -> float:
    # 函数内变量注解
    subtotal: float = price * quantity
    tax: float = subtotal * 0.1
    total: float = subtotal + tax
    return total

类属性注解

Python
class Person:
    # 类属性注解
    name: str
    age: int
    active: bool = True

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

# 实例访问
p = Person("Alice", 25)
print(p.name)  # Alice
print(p.active)  # True

None 类型注解

Python
from typing import Optional

# None 或其他类型
value: Optional[int] = None
value = 10  # 可以赋值 int

# 仅 None
empty: None = None

基本类型汇总

类型说明示例
int整数n: int = 10
float浮点数f: float = 0.5
str字符串s: str = "hello"
bool布尔值b: bool = True
None空值n: None = None
bytes字节b: bytes = b"data"

注解可见性

Python
# 注解可通过 __annotations__ 访问
def func(x: int, y: str) -> bool:
    local: int = 10
    return True

print(func.__annotations__)
# {'x': int, 'y': str, 'return': bool}

class MyClass:
    attr: str = "value"

print(MyClass.__annotations__)
# {'attr': str}

注解时机

Python
# 定义时注解
x: int = 10

# 分离注解和赋值
y: int
y = 20

# 条件赋值仍需注解
z: int
if condition:
    z = 10
else:
    z = 20

注解用途

Python
# 1. 提高可读性
name: str = "Alice"  # 清晰表明类型

# 2. IDE 智能提示
def process(data: str):
    # IDE 知道 data 是字符串
    return data.upper()

# 3. 静态类型检查
def add(a: int, b: int) -> int:
    return a + b
# mypy 可以检查类型正确性

要点总结

  • 使用内置类型 int、str、float、bool 注解变量
  • variable: type = value 是基本语法
  • 注解可分离于赋值,仅声明类型
  • 类属性注解定义类级别类型
  • __annotations__ 可访问注解信息
  • 注解不影响运行时,仅作提示
  • 用于提高可读性、IDE 提示、静态检查
  • 基本类型注解是类型系统的入门用法

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python typing模块
下一篇 → Python 复合类型注解
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库