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

如何获取Python类中@property装饰属性的返回类型注解?

提取@property装饰属性的返回类型注解

当你尝试用inspect.signature直接处理@property装饰的属性时,会因为获取到的是property对象而非原始方法而报错。解决思路是先判断目标成员是否为property类型,再获取其对应的getter方法来提取返回类型注解。

实现代码

import inspect

def return_type_extract(cls: type, prop_name: str) -> type:
    member = getattr(cls, prop_name)
    # 判断是否为property对象,若是则取其getter方法
    if isinstance(member, property):
        method = member.fget
    else:
        method = member
    return inspect.signature(method).return_annotation

# 测试示例
class Test:
    @property
    def foo(self) -> int:
        return 1
    
    def bar(self) -> str:
        return "test"

print(return_type_extract(Test, 'foo'))  # <class 'int'>
print(return_type_extract(Test, 'bar'))  # <class 'str'>

关键说明

  • @property装饰后的方法会被包装成property实例,它的fget属性指向原始的getter方法
  • 先通过isinstance(member, property)判断类型,切换到原始方法后,就能用inspect.signature正常提取返回注解
  • 这个函数同时兼容普通方法和@property属性的返回类型提取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:37:05