【发布时间】:2021-06-28 08:17:19
【问题描述】:
我想获取所有注释,包括属性注释。 我得到的只是为常规注释设置的注释:
from dataclasses import dataclass
@dataclass
class Test:
first: int = 1
@property
def second(self) -> int:
return 5
t = Test()
print(t.__annotations__)
# prints: {'first': <class 'int'>}
有没有办法将“第二”作为 __annotations__ 的一部分? 甚至可以强制它进入 __annotations__。
【问题讨论】:
-
我认为这只会出现在属性 getter 本身 -
Test.second.fget.__annotations__。上下文是什么,您打算如何使用注释? -
我继承自一个可以将对象保存为 json 的类,但它的工作方式是使用 __annotations__ 来确定从对象中保存的内容到 json 中。
标签: python oop python-dataclasses python-class