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

如何从Python类本身获取实例变量的类型提示?

解决方案

要直接调用get_type_hints(MyClass)得到实例属性的类型提示,你需要从类的__init__方法中提取参数注解,或者给类本身添加对应的注解。下面是两种可行的实现方式:

方法1:直接从__init__方法提取参数类型

利用inspect模块获取__init__方法的签名,排除self参数后提取类型注解:

from typing import get_type_hints
import inspect

class MyClass:
    def __init__(self, a: str, b: int):
        self.a: str = a
        self.b: int = b

# 获取__init__方法的参数签名
init_signature = inspect.signature(MyClass.__init__)
# 提取除self外的参数类型注解
type_hints = {
    param_name: param.annotation 
    for param_name, param in init_signature.parameters.items() 
    if param_name != "self"
}

print(type_hints)  # 输出: {'a': <class 'str'>, 'b': <class 'int'>}

方法2:给类添加__annotations__属性

将__init__方法的参数注解(排除return)赋值给类的__annotations__,这样后续调用get_type_hints(MyClass)就能直接得到目标结果:

from typing import get_type_hints

class MyClass:
    def __init__(self, a: str, b: int):
        self.a: str = a
        self.b: int = b

# 把__init__的参数注解(除return外)赋值给类的__annotations__
MyClass.__annotations__ = {
    key: value 
    for key, value in get_type_hints(MyClass.__init__).items() 
    if key != "return"
}

# 直接调用get_type_hints(MyClass)
print(get_type_hints(MyClass))  # 输出: {'a': <class 'str'>, 'b': <class 'int'>}

为什么原代码不行?

get_type_hints(类)默认只会读取类本身的__annotations__属性,而你定义的类型提示是在__init__方法的参数和实例属性上,类本身并没有这些注解,所以直接调用无法得到预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:14:56