如何获取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
相关产品推荐
相关产品推荐

