Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Abstract classes and Mixins in Python django

Tags:

python

oop

django

Can anyone please tell what is the difference between Abstract class and Mixin in Django. I mean if we are to inherit some methods from base class why there is separate terminology like mixins if that is just a class.

What is diff between baseclass and mixins

like image 935
Mirage Avatar asked Oct 10 '12 00:10

Mirage


Video Answer


1 Answers

In Python (and Django), mixin is a type of multiple inheritance. I tend to think of them as "specilist" classes that adds a particular functionality to the class that inheritates it (along with other classes). They aren't really meant to stand on their own.

Example with Django's 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}))

The added SingleObjectMixin will enable you to look up the author with just self.get_objects().


An abstract class in Python looks like this:

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!")

In languages like Java, there is an Interface contract which is an interface. However, Python doesn't have such and the closest thing you can get is an abstract class (you can also read on abc. This is mainly because Python utlizes duck typing which kind of removes the need for interfaces. Abstract class enables polymorphism just like interfaces do.

like image 104
K Z Avatar answered Sep 20 '22 11:09

K Z