[英]Use main class' properties in subclass?
sample: 样品:
from django.db import models
class BaseModel(models.Model):
CHOICES = ((0, 'nope'),
(1, 'yep'),)
# ...
class P(BaseModel):
p = models.SmallIntegerField(default=1, choices=BaseModel.CHOICES)
It's unnecessary to inherit the BaseModel
if I just use BaseModel.CHOICES
.But I must inherit it because some other column. 如果我只使用BaseModel
则不必继承BaseModel.CHOICES
但是我必须继承它,因为还有其他列。
How to let the P
inherit the CHOICES
property instead of using it's father's CHOICES
? 如何让P
继承CHOICES
属性而不是使用其父亲的CHOICES
?
In your example p
is not an inherited field, so it cannot "inherit" anything from BaseModel
. 在您的示例中, p
不是继承字段,因此它无法“继承” BaseModel
任何BaseModel
。 P
(the subclass) will inherit CHOICES
from BaseModel
but at the point where field p
is defined the P
class doesn't yet exists (it will only exists after the end of the class
statement body), so you cannot reference P.CHOICES
at this point, and since the name CHOICES
is not defined in the P
class statement's body, you cannot reference it either. P
(子类) 将继承CHOICES
从BaseModel
但其中场点p
定义的P
类不存在(这只会存在结束之后class
的语句体),所以你不能引用P.CHOICES
在此时,由于在P
类语句的主体中未定义名称CHOICES
,因此您也不能引用它。 So basically your snippet is the plain simple and obvious solution. 因此,基本上,您的摘录是简单明了的简单解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.