我有一个模型
BaseModel
以及它的几个子类
^{pr2}$
使用多表继承。将来我计划有几十个子类模型。在
所有子类都有方法的一些实现
do_something()
我如何从BaseModel实例调用do\u somthing?在
几乎相同的问题(没有解决方案)张贴在这里:
http://peterbraden.co.uk/article/django-inheritance
一个更简单的问题:如何在不检查所有可能的子类的情况下,将BaseModel instance解析为它的一个子类实例?在
Tags:
您将一直使用基类型的实例还是始终使用子类型的实例?如果是后者,则调用该方法,即使您有对基类型的引用,因为对象本身是一个子类型。在
由于Python支持duck typing,这意味着您的方法调用将被适当地绑定,因为子实例将真正拥有这个方法。在
注意EAFP代表Easier to Ask Forgiveness than Permission:
如果您想避免检查所有可能的子类,我唯一能想到的方法就是将与子类相关联的类名存储在基类上定义的字段中。基类可能具有如下方法:
这个答案并不能让我高兴,我也希望看到更好的解决方案,因为我很快就会面临类似的问题。在
我同意安德鲁的观点。在一些网站上,我们有一个类,它支持一大堆方法(但不支持字段(这是pre-ORM重构)),这些方法对大多数但不是所有的内容类都是通用的。他们利用hasattr来避开方法没有意义的情况。在
这意味着我们的大多数类被定义为:
基本上是一种混合型的东西。效果很好,易于维护。在
相关问题 更多 >
编程相关推荐