我有一个Generic类
class Generic:
raw_data = []
objects = dict()
和具体课程
class A(Generic):
raw_data = module.somethingA
class B(Generic):
raw_data = module.somethingB
我想将每个raw_data填充到类的每个对象dict上.
为此,我正在运行:
for object_type in (A,B):
for data in object_type.raw_data:
new_object = object_type(*data)
object_type.objects[id(new_object)] = new_object
但是,这不起作用,因为对象在A和B之间共享,我希望Generic的每个子类都有自己的对象.
如何在不必在每个子类上键入objects = dict()的情况下实现此目的?
我倾向于说这是一个需要元类的传统情况(为每个新类添加对象);是这种情况,还是有更简单的选择?
最佳答案
要么使用元类,要么使用类装饰器.
类装饰器可以简单地创建属性:
def add_objects(cls):
cls.objects = {}
return cls
@add_objects
class A(generic):
raw_data = module.somethingA
然而,这并没有真正增加任何东西;你只需用另一行(@add_objects)替换一行(objects = {}).
你可以在循环中添加对象:
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
或者复制它(读取属性可以检索父类属性或直接属性,这里没关系):
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
或从头开始创建字典:
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),)}