首页 > 解决方案 > 将具有其他类的类转换为字典中的属性

问题描述

我正在使用类和类作为父类的属性重新创建 json 文件的结构(这允许我使用 set 方法来简化过程):

class A(object):
    def __init__(self,):
        self.test = "something of A"
    def set_test():
        pass # some function here to set test from B



class B(object):
    def __init__(self,):
        self.test2 = A() # This is the A class that I wan't to access
        self.test3 = "something of B"



g = B()
g.__dict__

结果是这样的:

{'test2': <__main__.A at 0x7fda2d2fd9a0>, 'test3': 'something of B'}

相反,我希望将类的 dict 对象也作为属性:

{'test2': {'test': 'something of A'}, 'test3': 'something of B'}

我知道我可以做到:g['test2'] = g['test2'].__dict__但我想知道是否有一种自动方法可以将所有作为属性链接的类解析为字典。

注意:我希望能够从 B 访问 A 的方法,否则我会直接为 B 创建字典

标签: pythonclassdictionary

解决方案


推荐阅读