简体   繁体   English

在子类中使用主类的属性?

[英]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 (子类) 继承CHOICESBaseModel但其中场点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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM