且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django抽象模型vs简单Python mixins vs Python ABC

更新时间:2022-06-10 22:05:40

我会尝试简而言之,因为这很容易变成冗长的异议词:

I'll try to be reasonably brief, since this can easily turn into a lengthy diatribe:

ABC之所以出现是因为它们仅在Python 2.6中引入,并且Django开发人员有固定的路线图对于Python版本的支持(2.3支持仅在1.2中下降了。)

ABCs are out because they were only introduced in Python 2.6, and the Django developers have a set roadmap for Python version support (2.3 support was only dropped in 1.2).

对于对象继承混合器,它们在更多方面不是Pythonic,而不仅仅是降低可读性。 Django对 Model 对象使用 ModelBase 元类,该对象实际上在初始化时分析已定义的模型属性,并填充 Model._meta ,其中包含字段,元 c选项和其他属性。对于两种类型的模型都可以重用该框架。这也允许Django防止继承模型来覆盖抽象模型字段。

As for object-inheriting mixins, they would be less Pythonic in more ways than just reducing readability. Django uses a ModelBase metaclass for Model objects, which actually analyses the defined model properties on initialisation, and populates Model._meta with the fields, Meta options, and other properties. It makes sense to reuse that framework for both types of models. This also allows Django to prevent abstract model fields from being overriden by inheriting models.

我能想到的原因还有很多,它们全都是次要的,但是它们增加了使当前的实现更加Pythonic。不过,使用对象继承混合器并没有本质上的错误。

There's plenty more reasons I can think of, all of them minor in themself, but they add up to make the current implementation much more Pythonic. There's nothing inherently wrong with using object-inheriting mixins though.