python - 将具有其他类的类转换为字典中的属性
问题描述
我正在使用类和类作为父类的属性重新创建 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 创建字典
解决方案
推荐阅读
- javascript - 将对象追加/添加/取消移动到来自 api 的响应的开头
- elasticsearch - query_string 中的通配符搜索
- sql-server - 根据文件日期获取 SQL Server 中的先前记录
- c++ - 如何从操作“newaccount”中获取 EOS 公钥
- laravel - 如何使用带有 Lighthouse 参数的自定义 Laravel 规则
- c# - 以编程方式从项目资源安装内置字体,C# winforms
- firebase - Firebase 动态链接查询参数始终为空
- javascript - 使用 JavaScript 从表格单元格中提取数据
- mongodb - 无法连接到入口 k8s 后面的 mongo-express
- macos - mach_wait_until() 可以被信号打断吗?