[英]Django, inherit models.Model first or non model class first?
Sometimes I see 有时候我看到
class Foo(models.Model, NonModelCls):
pass
Other times, I see 有时候我看
class Bar(NonModelCls, models.Model):
pass
What's the difference between the two and when should I use each over another? 两者之间有什么区别?何时应相互使用?
It depends on what you have in NonModelCls
. 这取决于您在
NonModelCls
拥有什么。 Search order for attributes and methods are from left to right ( https://docs.python.org/3/tutorial/classes.html?highlight=inheritence#multiple-inheritance ). 属性和方法的搜索顺序从左到右( https://docs.python.org/3/tutorial/classes.html?highlight=inheritence#multiple-inheritance )。
Let's say you have these classes: 假设您有以下课程:
class A:
def __init__():
print('A')
super(A, self).__init__()
class B:
def __init__():
print('B')
super(B, self).__init__()
class C(A,B):
pass
class D(B,A):
pass
Then calling C and D will result in: 然后调用C和D将导致:
>>>C()
A
B
<__main__.C object at 0x7f51d3efe0f0>
>>>D()
B
A
<__main__.D object at 0x7f51d3efe0b8>
So in your case, if NonModelCls
has a method with same name as one of models.Model
methods, like save
, then it will override Model.save
in Bar
class, while it gets ignored in Foo
class. 因此,在您的情况下,如果
NonModelCls
具有与models.Model
方法之一相同的名称的方法,例如save
,则它将覆盖Bar
类中的Model.save
,而在Foo
类中将其忽略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.