How to represent class and nested class attributes in dict of dicts?
class Serial:
def read(self):
dic = {}
for key, val in self.__class__.__dict__.items():
if not key.startswith("__") and not callable(val):
dic[key] = val
for key, val in self.__dict__.items():
dic[key] = val.read() if hasattr(val, "read") else val
return dic
class A(Serial):
aa = 1
class B(Serial):
bb = 2
class C(Serial):
c1 = 3
a = A()
def __init__(self):
self.c2 = 4
self.b = B()
c = C()
c.read() # {'c1': 3, 'a': <__main__.A at 0x2b5f43ba1d0>, 'c2': 4, 'b': {'bb': 2}}
The above works only if I move c1
and a
into __init__
.
class C(Serial):
def __init__(self):
self.c1 = 3
self.a = A()
self.c2 = 4
self.b = B()
c = C()
c.read() # {'c1': 3, 'a': {'aa': 1}, 'c2': 4, 'b': {'bb': 2}}
Is there a simpler way?