You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

成员变量注解存储位置及特定变量注解所属__annotations__字典查询

Python成员变量注解的存储位置

咱们把这个问题拆成两部分说,这确实是Python类型注解里容易搞混的点:

1. 成员变量注解到底存在哪儿?

要看你是怎么定义这个变量的:

  • 类体里直接定义的类变量:不管有没有给默认值,注解都会存在类自身的__annotations__字典里。比如:
class MyClass:
    x: int = 5
    y: str

print(MyClass.__annotations__)
# 输出: {'x': <class 'int'>, 'y': <class 'str'>}
  • 实例方法(比如__init__)里定义的实例变量:这类注解会绑定在该方法的__annotations__字典上,既不在类的注解里,也不会跑到实例对象本身的属性里。举个例子:
class MyClass:
    def __init__(self):
        self.x: int = 5
        self.where_is_this_vars_annotation_stored: str

# 查看__init__方法的注解字典
print(MyClass.__init__.__annotations__)
# 输出: {'x': <class 'int'>, 'where_is_this_vars_annotation_stored': <class 'str'>}

2. 为什么找不到那个变量的注解归属?

你说能看到x的类型提示,但不确定where_is_this_vars_annotation_stored的注解属于哪个字典,大概率是因为:

  • x是类级别的变量,它的注解在类的__annotations__里,所以很容易找到;
  • 而where_is_this_vars_annotation_stored是在实例方法里定义的实例变量,它的注解藏在方法的__annotations__里,平时我们很少去查看方法的注解字典,所以会觉得找不到。

另外提一句:实例对象本身默认是没有__annotations__字典的,除非你手动给它添加。VS Code、PyCharm这类工具的类型提示,会自动从对应的注解字典里读取信息——类变量读类的注解,实例变量读方法的注解,所以你能看到提示,但注解的存储位置藏得比较深而已。

内容的提问来源于stack exchange,提问作者acushner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:17:30