python - 如何在 asdict 中获取@property 方法?
问题描述
我有类似的东西:
from attr import attrs, attrib
@attrs
class Foo():
max_count = attrib()
@property
def get_max_plus_one(self):
return self.max_count + 1
现在当我这样做时:
f = Foo(max_count=2)
f.get_max_plus_one =>3
我想将其转换为 dict:
{'max_count':2, 'get_max_plus_one': 3}
当我使用时,attr.asdict(f)
我没有得到@property
. 我只得到
{'max_count':2}
.
实现上述目标的最干净方法是什么?
解决方案
通常,您必须遍历类属性并检查实例,property
然后__get__
使用实例调用属性方法。所以,像:
In [16]: class A:
...: @property
...: def x(self):
...: return 42
...: @property
...: def y(self):
...: return 'foo'
...:
In [17]: a = A()
In [18]: vars(a)
Out[18]: {}
In [19]: a.x
Out[19]: 42
In [20]: a.y
Out[20]: 'foo'
In [21]: {n:p.__get__(a) for n, p in vars(A).items() if isinstance(p, property)}
Out[21]: {'x': 42, 'y': 'foo'}
推荐阅读
- java - 实现接口时如何初始化对象
- ruby-on-rails - 使用 Turbolinks 时无法运行特定于页面的 javascript 包
- c# - Azure Function App 错误“无法解析远程名称”
- ruby-on-rails - 如何在 where 查询中使用参数 - Ruby?
- c - 等效表达式 memset 和数组
- angularjs - MVC 控制器方法未从 $http post 接收 json 数据
- ios - 如何在其他开发人员设备中安装我的 xcode 项目以进行测试
- android - 当我尝试使用 FloatingActionButton 打开 Main2Activity 时应用程序崩溃
- python - Python Bot 中的子命令
- c - 带有存储类说明符的空声明/声明说明符中有两种或多种数据类型