Use main class' properties in subclass?

时间:2015-06-26 09:35:50

标签: python django python-2.7 python-3.x django-models

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.

How to let the P inherit the CHOICES property instead of using it's father's CHOICES?

1 个答案:

答案 0 :(得分:0)

In your example p is not an inherited field, so it cannot "inherit" anything from 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. So basically your snippet is the plain simple and obvious solution.