class A:
attr = {'a': 1}
class B(A):
attr = {'b': 2} #overrides A.attr
我想要的是一种聚合字典的方法。我能想到的选项只有以下几种:
- Ignore that disconcerting feeling and copy everything by hand.
Manually adding the dictionaries:
class B(a): attr = dict(list(six.iteritems(A.attr)) + list(six.iteritems({ 'b': 2 })))
Note
'b': 2
must come second so its keys shadowA
's.This must reference
A
explicitly (is there some way to get this withsuper
?). It also needs this kind of micro inheritance to be applied manually.This is also something that could be achieved with metaclasses. I've seen it done in
DeclarativeFieldsMetaclass
in django. The idea is to have the metaclass handle dictionary merging for a specific attribute.This is far more work. Also, as it introduces magic that doesn't normally happen in python, this might be considered a poor option. I also prefer to not use metaclasses unless necessary to avoid conflicts.
One major advantage is the user doesn't need to manually aggregate the attribute data.
还有其他的方法吗?
我想知道其他人对每种方法在良好的编程实践方面的看法。
在我的情况下,我正在使用django-betterforms
中的MultiModelForm
,有一个基础表单,只包含几个ModelForm
,但想要扩展它。 我不认为继承类应该需要在父类的form_classes
属性中复制ModelForm
。
是应该由用户来管理继承,如选项2,还是应该由MultiModelForm
使用元类自动处理,如选项3?每个选项是否存在其他未讨论的问题?
attr = {**A.attr, 'b': 2}
。 - user2357112