Django抽象模型vs简单Python mixins vs Python ABC [英] Django Abstract Models vs simple Python mixins vs Python ABCs

查看:73
本文介绍了Django抽象模型vs简单Python mixins vs Python ABC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是另一个问题提示的问题

Django提供了抽象基类功能(与Python中的ABC类不同吗?),这样就可以创建一个可以继承但不能继承的模型(Django的models.Model)。该模型在数据库中具有实际表。可以通过在模型的Meta类中设置抽象属性来触发此行为。

Django provides Abstract base classes functionality (which are not to same as ABC classes in Python?) so that one can make a Model (Django's models.Model) from which one can inherit, but without that Model having an actual table in the database. One triggers this behavior by setting the 'abstract' attribute in the Model's Meta class.

现在的问题是:Django为什么要用这种方式解决它?为什么需要这种特殊的抽象基类模型?为什么不通过仅继承对象类并将其与现有模型混合来进行模型混合?还是可以通过Python ABC的任务来做到这一点? (请注意,您对Python中的ABC类不是很熟悉,我的无知可能会显示在这里)

Now the question: why does Django solve it this way? Why the need for this special kind of 'Abstract base class' Model? Why not make a Model mixin by just inheriting from the object class and mixing that in with an existing Model? Or could this also by a task for Python ABCs? (mind you I'm not very familiar with ABC classes in Python, my ignorance might show here)

推荐答案

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

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.

这篇关于Django抽象模型vs简单Python mixins vs Python ABC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆