I got a class Car
that has an attribute called parts
. This attribute is a list that will be filled in the process of my program. parts
will contain a list other type of objects, like Engine
, Battery
, Wheels
and so on, that have their own attributes but does not inherits from the Car
.
After I will build my Car
object instance and fill its parts
with all necessary objects, I would like convert it to dictionaries (easy to search and for comparison) and further to JSON. I found out how __dict__()
works for custom objects and this makes it very quick and elastic without defining it in the Car
class. But the __dict__
does not recursively creates dictionary for the objects inside the attribute parts.
How should I approach this problem? Should I define my own __dict__()
method in class Car
or there is another way, that will keep my classes elastic?
SOLUTION:
I have moved forward thanks to @enzo. He didn't put the right answer cause he didn't assumed, that the parts
attribute of Car
class is a list of parts. And sometimes, Car
can have other attribute that is a list hat does not have __dict__
attribute. So there needs to be more checks.
Below my code. cars
is a list of all Car
objects, cars_to_dict
will keep my current "snapshoot" of my cars
list:
cars = list()
cars_to_dict = dict()
for car in cars:
for k, v in car.__dict__.items():
if type(v) == type([list()]):
cars_to_dict = cars_to_dict | { k : list() }
for a in v:
if type(a) == type(Whell()):
cars_to_dict[k].append(a.__dict__)
else:
cars_to_dict[k].append(a)
else:
cars_to_dict = cars_to_dict | { k : list() }