简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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