从具有相同父级但不同子级的抽象类的多重继承?詹戈 [英] Multiple inheritance from abstract classes with same parent but different child? django

查看:80
本文介绍了从具有相同父级但不同子级的抽象类的多重继承?詹戈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了几个线程,并且知道django肯定可以有多个抽象类.但是我看到的几乎所有样本都是...

I have read few threads and know that for sure django can have multiple abstract classes. But pretty much all the samples I saw are...

class AbsOne(models.Model):
    pass
class AbsTwo(models.Model):
    pass

class AbsThree(AbsOne, AbsTwo):
    pass

但是如果我有类似的东西...

but what if I have something like...

class AbsOne(models.Model):
    pass

class AbsTwo(AbsOne):  // this actually inheritance AbsOne
    pass
class AbsThree(AbsOne):  // this inheritance AbsOne
    pass

如果我都需要继承AbsTwo, AbsThree,但是这两个也都继承到同一个父级,该怎么办?

What if I need to inheritance both AbsTwo, AbsThree but these two are also inheritance to the same parent.

class AbsFour(AbsTwo, AbsThree):
    pass

这是可行的,没有任何冲突或多余的字段吗?

Is this doable without any conflict or extra fields?

谢谢.

推荐答案

就像Python的子类一样,Django模型也可以 从多个父模型继承.请记住,普通的Python 名称解析规则适用.特定的第一个基类 出现的名称(例如Meta)将是所使用的名称;例如, 这意味着,如果多个父级包含一个元类,则只有 第一个将被使用,而其他所有将被忽略.

Just as with Python’s subclassing, it’s possible for a Django model to inherit from multiple parent models. Keep in mind that normal Python name resolution rules apply. The first base class that a particular name (e.g. Meta) appears in will be the one that is used; for example, this means that if multiple parents contain a Meta class, only the first one is going to be used, and all others will be ignored.

https://docs.djangoproject.com/zh/1.11/topics/db/models/#multiple-inheritance

这是可能的,但是它有一些限制(例如(覆盖父类和元类中的字段)和Django ORM),或者类的模型方式在体系结构上与常规python继承有所不同,请仔细阅读文档中提到的内容并尝试为了简单起见.

It's possible but it has some restrictions like ( overriding fields in parent class and meta classes ) and in Django ORM or the model way of classes is a bit different in architecture than regular python inheritance, read carefully what the documentation mentions and try to keep it simple.

...有用的主要用例是混合"类:添加 每个继承该类的类的特定额外字段或方法 混入.尝试使继承层次结构保持简单和 尽可能简单明了,这样您就不必为工作而苦恼 特定信息来自何处

... The main use-case where this is useful is for "mix-in" classes: adding a particular extra field or method to every class that inherits the mix-in. Try to keep your inheritance hierarchies as simple and straightforward as possible so that you won’t have to struggle to work out where a particular piece of information is coming from

添加了另一个引号:)

这篇关于从具有相同父级但不同子级的抽象类的多重继承?詹戈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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