What is the actual difference in using composition versus inheritance?
I am trying to learn inheritance versus composition the hard way. So far, I have understood that composition involves using object reference inside a class. So I asked myself, why did not we choose to use composition in Django for, say, ModelViewSet, like:
class MyViewSet:
queryset = ...
viewset = ModelViewSet()
and then, any get request will be redirected to MyViewSet.list(self) having a call to self.viewset.list(self)?
Maybe this SO post about Inheritance vs Composition answers the "difference" part of your question.
any get request will be redirected to MyViewSet.list(self) having a call to self.viewset.list(self)
And who would be calling self.viewset.list(self)? MyViewSet is an "empty" class without its own methods at all. There is no MyViewSet.list that could be called. Unless you want to write a def list(self): ... for each of your view classes every time?
No, if you want MyViewSet to behave in some way without writing that behaviour into it, it must inherit something from somewhere. Inheritance makes perfect sense for these cases. You inherit a complete ViewSet with some very extensive behaviour, and only customise its behaviour by adjusting a couple of attributes, or maybe overriding a method or three.
Composition makes more sense when your class "isn't a thing". In the case of ViewSets, the ViewSet isn't a model or queryset. It would make no sense for the ViewSet to have any methods that make a model or queryset work. Thus you're setting the queryset attribute to an instance of the particular queryset it'll need, but you're not letting it inherit that queryset. Because the ViewSet doesn't need to behave like a queryset, it just needs to get access to an object that does.
if someone would like to create own class using composition with your MyViewSet
class OtherViewSet:
queryset = ...
viewset = MyViewSet()
then it would have to write self.viewset.viewset.list(self) (and this makes it too long for me)
And using inheritance in OtherViewSet and MyViewSet it would always have self.list(self)