2012-02-16 48 views
0

为什么这段代码不起作用? 我看到在调试器(PyCharm)初始化行被执行,但没有更多。 我试图把那里提出异常确定,再次没有发生。Multipple继承和Django表格

class polo(object): 
    def __init__(self): 
     super(polo, self).__init__() 
     self.po=1  <- this code is newer executed 

class EprForm(forms.ModelForm, polo): 
    class Meta: 
     model = models.Epr 
+0

为什么它不工作?你得到了什么错误? – Marcin 2012-02-16 16:14:49

+0

绝对没有错误。该代码根本不被执行。 – user1214179 2012-02-17 00:08:40

回答

1

您使用multiple inheritance所以一般Python会寻找在左到右的顺序方法。因此,如果你的班级没有__init__,它会在ModelFormpolo中找到它(只有找不到)。在您的代码中,polo.__init__从不会被调用,因为ModelForm.__init__被调用。

同时调用基类的构造函数使用明确的构造函数调用:

class EprForm(forms.ModelForm, polo): 

    def __init__(self, *args, **kwargs) 
     forms.ModelForm.__init__(self, *args, **kwargs) # Call the constructor of ModelForm 
     polo.__init__(self, *args, **kwargs) # Call the constructor of polo 

    class Meta: 
     model = models.Epr 
+0

非常感谢你。现在,当我看到你的答案时就符合逻辑。我不知道为什么一个假设__init__是一些特殊的方法,并且会被每个继承类调用。 并从http://stackoverflow.com/questions/1401661/python-list-all-base-classes-in-a-hierarchy的知识,我将能够调用所有基类的__init__函数。 伟大的工作! – user1214179 2012-02-18 12:44:22