2014-02-19 22 views
0

我正在使用django,但这是一个相当通用的python问题。Python多类层次结构__init__没有被执行

我已经定义了一个类,我打算用来从django.forms扩展ModelForm和Form类。

的代码看起来是这样的:

class FormMixin(object): 

    def __init__(self, *args, **kwargs): 
     """ every method ocurrence must call super """ 
     super(FormMixin, self).__init__(*args, **kwargs) 
     self.new_attr = 'This is an attribute' 



class ModelFormAdapter(forms.ModelForm): 
""" I use this class so __init__ signatures match """ 
    def __init__(self, *args, **kwargs): 
     """ every method ocurrence must call super """ 
     super(ModelFormAdapter, self).__init__(*args, **kwargs)   


class BaseModelForm(ModelFormAdapter, FormMixin): 

    def __init__(self, *args, **kwargs): 
     """ BaseModelForm never gets the attribute new_attr """ 
     super(BaseModelForm, self).__init__(*args, **kwargs) 

我甚至调试这和FormMixin INIT方法不会被调用。我究竟做错了什么?我想实现的是一些属性添加到窗体和预处理字段标签和CSS类

回答

2

这是因为ModelFormAdapter的祖先之一(BaseForm),不叫super和链断裂。首先将FormMixin置于父列表中。