【问题标题】:Does overriding an abstract base class attribute affect other child classes?覆盖抽象基类属性会影响其他子类吗?
【发布时间】:2018-07-26 10:54:11
【问题描述】:

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

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

它是否也会影响其他子类字段?

【问题讨论】:

    标签: python django django-models django-1.8


    【解决方案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!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 2011-08-14
      • 2023-03-04
      • 1970-01-01
      • 2015-02-25
      相关资源
      最近更新 更多