Django继承:如何为所有子类使用一个方法?

2024-10-03 02:38:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型

BaseModel

以及它的几个子类

^{pr2}$

使用多表继承。将来我计划有几十个子类模型。在

所有子类都有方法的一些实现

do_something()

我如何从BaseModel实例调用do\u somthing?在

几乎相同的问题(没有解决方案)张贴在这里:
http://peterbraden.co.uk/article/django-inheritance

一个更简单的问题:如何在不检查所有可能的子类的情况下,将BaseModel instance解析为它的一个子类实例?在


Tags: 实例方法模型http解决方案子类dosomething
3条回答

您将一直使用基类型的实例还是始终使用子类型的实例?如果是后者,则调用该方法,即使您有对基类型的引用,因为对象本身是一个子类型。在

由于Python支持duck typing,这意味着您的方法调用将被适当地绑定,因为子实例将真正拥有这个方法。在

A pythonic programming style which determines an object’s type by inspection of its method or attribute signature rather than by explicit relationship to some type object (“If it looks like a duck and quacks like a duck, it must be a duck.”) By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). (Note, however, that duck-typing can be complemented with abstract base classes.) Instead, it typically employs hasattr() tests or EAFP programming.

注意EAFP代表Easier to Ask Forgiveness than Permission

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

如果您想避免检查所有可能的子类,我唯一能想到的方法就是将与子类相关联的类名存储在基类上定义的字段中。基类可能具有如下方法:

def resolve(self):
    module, cls_name = self.class_name.rsplit(".",1)
    module = import_module(module)
    cls = getattr(module, cls_name)
    return cls.objects.get(pk=self.pk)

这个答案并不能让我高兴,我也希望看到更好的解决方案,因为我很快就会面临类似的问题。在

我同意安德鲁的观点。在一些网站上,我们有一个类,它支持一大堆方法(但不支持字段(这是pre-ORM重构)),这些方法对大多数但不是所有的内容类都是通用的。他们利用hasattr来避开方法没有意义的情况。在

这意味着我们的大多数类被定义为:

class Foo(models.Model, OurKitchenSinkClass):

基本上是一种混合型的东西。效果很好,易于维护。在

相关问题 更多 >