覆盖抽象基类属性是否会影响其他子类?

时间:2018-02-15 16:00:52

标签: python django django-models django-1.8

如果我改变抽象基类字段的属性,如

Classname._meta.get_field(fieldname).attribute = 'value'

它会影响其他子类字段吗?

1 个答案:

答案 0 :(得分:1)

tl; dr - 这个变化并没有神奇地反映回以前对抽象类的使用。

取决于您更改属性的位置。如果在定义子类之前执行此操作,则更改将反映在该特定子类中,但如果在定义子类后执行此操作,则不会影响子类的属性。

class Foo(models.Model):
    char = models.CharField(default='world!', max_length=32)

    class Meta:
        abstract = True

class Bar1(Foo):
    pass

print('bar1 -', Bar1._meta.get_field('char').default)

Foo._meta.get_field('char').default = 'hello!'
print('changed to hello!')

class Bar2(Foo):
    pass

print('bar1 -', Bar1._meta.get_field('char').default)
print('bar2 -', Bar2._meta.get_field('char').default)

Foo._meta.get_field('char').default = 'magic!'
print('changed to magic!')

class Bar3(Foo):
    pass

print('bar1 -', Bar1._meta.get_field('char').default)
print('bar2 -', Bar2._meta.get_field('char').default)
print('bar3 -', Bar3._meta.get_field('char').default)

给出以下输出 -

bar1 - world!
changed to hello!
bar1 - world!
bar2 - hello!
changed to magic!
bar1 - world!
bar2 - hello!
bar3 - magic!