使子类有自己的类属性

2024-06-16 12:37:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类Generic

class Generic:
    raw_data = []
    objects = dict()

混凝土类

class A(Generic):
    raw_data = module.somethingA

class B(Generic):
    raw_data = module.somethingB

我想将每个raw_data填充到类的每个objectsdict中。 对此,我正在运行:

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

但是,这不起作用,因为objectsAB之间共享,我希望Generic的每个子类都有自己的对象。你知道吗

如何在不必在每个子类上键入objects = dict()的情况下实现这一点?你知道吗

我倾向于说,这是一个传统的情况,其中需要一个元类(即向每个新类添加objects);是这样的情况,还是有更简单的选择?你知道吗


Tags: innewfordatarawobjectsobjecttype
2条回答

我认为这里不需要元类。为什么不在填充循环中的每个子类之前复制父类对象呢?你知道吗

for object_type in (A, B):
     # copy Generic.objects onto object_type.objects here
     object_type.objects = Generic.objects.copy()
     for data in object_type.raw_data:
         new_object = object_type(*data)
         object_type.objects[id(new_object)] = new_object

此外,如果需要,还可以修改为使用super和/或deepcopy。你知道吗

要么使用元类,要么使用类装饰器。你知道吗

类装饰器可以简单地创建属性:

def add_objects(cls):
    cls.objects = {}
    return cls

@add_objects
class A(generic):
    raw_data = module.somethingA

但是,这并没有真正添加任何内容;只需将一行(objects = {})替换为另一行(@add_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),)}

相关问题 更多 >