Use a metaclass or use a class decorator.
The class decorator can simply create an attribute:
def add_objects(cls): cls.objects = {} return cls @add_objects class A(generic): raw_data = module.somethingA
It really adds nothing; you just replace one line ( objects = {} ) with another ( @add_objects ).
You can simply add an object to your loop:
for object_type in (A, B): if 'objects' not in vars(object_type): object_type.objects = {} for data in object_type.raw_data: new_object = object_type(*data) object_type.objects[id(new_object)] = new_object
or copy it (reading the attribute can get the attribute of the parent class or direct attribute, it does not matter here):
for object_type in (A, B): object_type.objects = object_type.objects.copy() for data in object_type.raw_data: new_object = object_type(*data) object_type.objects[id(new_object)] = new_object
or create a dictionary from scratch:
for object_type in (A, B): object_type.object = { id(new_object): new_object for data in object_type.raw_data for new_object in (object_type(*data),)}
source share