【问题标题】:Multiple inheritance and Django Form多重继承和 Django 表单
【发布时间】:2012-03-08 00:26:19
【问题描述】:

为什么这段代码不起作用? 我在调试器(PyCharm)中看到 init 行已执行,但仅此而已。 我试图放在那里引发异常以确保真的没有发生任何事情。

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

【问题讨论】:

  • 为什么不起作用?您遇到什么错误等?
  • 绝对没有错误。代码根本没有执行。

标签: python django-forms


【解决方案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

【讨论】:

  • 非常感谢。现在,当我看到您的回答时,这是合乎逻辑的。我不知道为什么假设 init 是一些特殊方法,并且会为每个继承的类调用。通过stackoverflow.com/questions/1401661/… 的知识,我将能够调用所有基类的 init 函数。干得好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2014-11-03
  • 2018-09-19
  • 1970-01-01
  • 2017-10-14
相关资源
最近更新 更多