gpt4 book ai didi

python - 切换祖先顺序会破坏初始化吗?

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:26 24 4
gpt4 key购买 nike

这是来自 Django 应用程序,以自定义形式使用多重继承:

from django import forms

class CommonForm(forms.ModelForm):
class Meta:
model = MyModel

def __init__(self, request, *args, **kwargs):
print 'CommonForm.__init__'
super(CommonForm, self).__init__(request, *args, **kwargs)
print 'CommonForm.__init__ FINISHED'
self._request = request

class MyMixin(object):
def __init__(self, *args, **kwargs):
print 'MyMixin.__init__'
super(MyMixin, self).__init__(*args, **kwargs)
print 'MyMixin.__init__ FINISHED'

class CustomForm(CommonForm, MyMixin):
def __init__(self, request, *args, **kwargs):
print 'CustomForm.__init__'
super(CustomForm, self).__init__(request, *args, **kwargs)
print 'CustomForm.__init__ FINISHED'

# weird initialization:
frm = CustomForm(http_request)

# outputs:
CustomForm.__init__
CommonForm.__init__
CommonForm.__init__ FINISHED
CustomForm.__init__ FINISHED

什么会导致 MyMixin.__init__ 被跳过?!没有错误消息,没有抛出异常,什么都没有......

如果我将类继承顺序切换为

class CustomForm(MyMixin, CommonForm):

所有初始化器都按预期突然调用:

frm = CustomForm(http_request)

CustomForm.__init__
MyMixin.__init__
CommonForm.__init__
CommonForm.__init__ FINISHED
MyMixin.__init__ FINISHED
CustomForm.__init__ FINISHED

谁能解释一下这是怎么回事吗?

最佳答案

我不确定为什么会发生这种情况,但我确实知道在使用多重继承时不应该使用 super(),而是应该:

    CommonForm.__init__(request, *args, **kwargs)
MyMixin.__init__(*args, **kwargs)

这是一个很好的例子:http://www.python-course.eu/python3_multiple_inheritance.php

关于python - 切换祖先顺序会破坏初始化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32238581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com