gpt4 book ai didi

python - 将具有属性的 python 对象转换为字典

转载 作者:太空宇宙 更新时间:2023-11-03 20:52:17 25 4
gpt4 key购买 nike

我想知道如何从字典转换 python 对象(使用 python3 顺便说一句)。我意识到这个问题已经被提出(并回答)了( here )。但是,在我的例子中,对象完全按照 @property 值给出,例如:

class Test: 
@property
def value(self):
return 1.0

关于转换为字典:Test 类的 __dict__ 字典为空,因此 vars功能未按预期工作:

>>> vars(Test()) 
{}

不过,我可以使用 gettattr(Test(), 'value') 来获取 1.0,所以值已存在。

注意:我提出这个显然是人为的示例的原因是我试图将 cython cdef class (包含参数)转换为字典。使用 cython 用属性包装 c 结构的推荐方法确实基于 properties .

最佳答案

我认为你可以使用dir:

a = Test()
dir(a)

输出:

['__doc__', '__module__', 'value']

所以你也许可以这样做:

d = {}
for attr in dir(a):
if not attr.startswith("__"):
d[attr] = getattr(a, attr)

输出:

d = {'value': 1.0}

关于python - 将具有属性的 python 对象转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56240995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com