【发布时间】:2012-10-10 00:21:28
【问题描述】:
谁能告诉我 Django 中的 Abstract 类和 Mixin 有什么区别。 我的意思是,如果我们要从基类继承一些方法,为什么还有单独的术语,比如 mixins,如果那只是一个类。
baseclass 和 mixins 有什么区别
【问题讨论】:
谁能告诉我 Django 中的 Abstract 类和 Mixin 有什么区别。 我的意思是,如果我们要从基类继承一些方法,为什么还有单独的术语,比如 mixins,如果那只是一个类。
baseclass 和 mixins 有什么区别
【问题讨论】:
在 Python(和 Django)中,mixin 是一种多重继承。我倾向于想到他们 作为“专家”类,将特定功能添加到该类中 继承它(连同其他类)。他们并不是真的要站立 他们自己的。
以 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}))
添加的SingleObjectMixin 将使您能够仅使用self.get_objects() 查找author。
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!")
在像 Java 这样的语言中,有一个 Interface 合约,它是
界面。然而,Python 没有你能做到的 最接近的东西
get 是一个抽象类(您也可以阅读 abc。这主要是因为 Python 使用了 duck typing,这消除了对接口的需求。抽象类像接口一样支持多态性。
【讨论】: