When reading the book Django Unleashed, I came across this code snippet. I was wondering why NewsLinkGetObjectMixin can access the class variable startup_slug_url_kwarg, which is define in another base class StartupContextMixin?
class NewsLinkGetObjectMixin():
def get_object(self, queryset=None):
startup_slug = self.kwargs.get(
self.startup_slug_url_kwarg)
newslink_slug = self.kwargs.get(
self.slug_url_kwarg)
return get_object_or_404(
NewsLink,
slug__iexact=newslink_slug,
startup__slug__iexact=startup_slug)
class StartupContextMixin():
startup_slug_url_kwarg = 'startup_slug'
startup_context_object_name = 'startup'
def get_context_data(self, **kwargs):
startup_slug = self.kwargs.get(
self.startup_slug_url_kwarg)
startup = get_object_or_404(
Startup, slug__iexact=startup_slug)
context = {
self.startup_context_object_name:
startup,
}
context.update(kwargs)
return super().get_context_data(**context)
class NewsLinkCreate(NewsLinkGetObjectMixin, StartupContextMixin, CreateView):
When you inherit a class from several base classes, inherited class can access all attributes of the base classes.
NewsLinkCreate
is inherited from both NewsLinkGetObjectMixin
and StartupContextMixin
. So, when you call method get_object
on the NewsLinkCreate
instance, it can access variables both from NewsLinkGetObjectMixin
and StartupContextMixin
because NewsLinkCreate
is inherited from both classes. All attributes of both mixins are added to the class NewsLinkCreate
.