擅长:python、mysql、java
<p>要么使用元类,要么使用类装饰器。你知道吗</p>
<p>类装饰器可以简单地创建属性:</p>
<pre><code>def add_objects(cls):
cls.objects = {}
return cls
@add_objects
class A(generic):
raw_data = module.somethingA
</code></pre>
<p>但是,这并没有真正添加任何内容;只需将一行(<code>objects = {}</code>)替换为另一行(<code>@add_objects</code>)。你知道吗</p>
<p>只需在循环中添加对象:</p>
<pre><code>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
</code></pre>
<p>或者复制它(读取属性可以检索父类属性或直接属性,这里不重要):</p>
<pre><code>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
</code></pre>
<p>或者从头开始创建字典:</p>
<pre><code>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),)}
</code></pre>