Python django中的抽象类和Mixins有什么区别

Ran*_*ngh 7 python oop django

任何人都可以告诉我们在Django中抽象类和Mixin有什么区别.我的意思是,如果我们要从基类继承一些方法,为什么有像mixin这样的单独术语,如果它只是一个类.

baseclass和mixins之间的差异是什么

K Z*_*K Z 6

在Python(和Django)中,mixin是一种多重继承.我倾向于认为它们是"specilist"类,它们为继承它的类(以及其他类)添加了特定的功能.它们并不是真正意义上的独立.

Django的例子SingleObjectMixin,

# views.py
from django.http import HttpResponseForbidden, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic import View
from django.views.generic.detail import SingleObjectMixin
from books.models import Author

class RecordInterest(View, SingleObjectMixin):
    """Records the current user's interest in an author."""
    model = Author

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseForbidden()

        # Look up the author we're interested in.
        self.object = self.get_object()
        # Actually record interest somehow here!

        return HttpResponseRedirect(reverse('author-detail', kwargs={'pk': self.object.pk}))
Run Code Online (Sandbox Code Playgroud)

所添加SingleObjectMixin将使你来查找authorself.get_objects().


Python中的抽象类看起来像这样:

class Base(object):
    # This is an abstract class

    # This is the method child classes need to implement
    def implement_me(self):
        raise NotImplementedError("told you so!")
Run Code Online (Sandbox Code Playgroud)

在像Java这样的语言中,有一个Interface契约是一个 接口.然而,Python没有这样的,你可以得到的最接近的东西是一个抽象类(你也可以阅读abc.这主要是因为Python使用了鸭子类型,这种类型消除了对接口的需求.抽象类使得多态性就像接口做.