簡體   English   中英

Make子類有自己的class屬性

[英]Make subclass have its own class attribute

我有一個Generic

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

和具體課程

class A(Generic):
    raw_data = module.somethingA

class B(Generic):
    raw_data = module.somethingB

我想將每個raw_data填充到類的每個objects 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

但是,這不起作用,因為objectsAB之間共享,我希望Generic每個子類都有自己的對象。

如何在不必在每個子類上鍵入objects = dict()情況下實現此objects = dict()

我傾向於說這是一個需要元類的傳統情況(為每個新類添加objects ); 是這種情況,還是有一個更簡單的選擇?

要么使用元類,要么使用類裝飾器。

類裝飾器可以簡單地創建屬性:

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),)}

我認為這里不需要元類。 為什么不在填充循環中的每個子類之前復制父類對象?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM