How does Python's super() work with multiple inheritance?

后端 未结 16 2151
孤街浪徒
孤街浪徒 2020-11-21 05:19

I\'m pretty much new in Python object oriented programming and I have trouble understanding the super() function (new style classes) especially when it comes to

16条回答
  •  野性不改
    2020-11-21 05:28

    Maybe there's still something that can be added, a small example with Django rest_framework, and decorators. This provides an answer to the implicit question: "why would I want this anyway?"

    As said: we're with Django rest_framework, and we're using generic views, and for each type of objects in our database we find ourselves with one view class providing GET and POST for lists of objects, and an other view class providing GET, PUT, and DELETE for individual objects.

    Now the POST, PUT, and DELETE we want to decorate with Django's login_required. Notice how this touches both classes, but not all methods in either class.

    A solution could go through multiple inheritance.

    from django.utils.decorators import method_decorator
    from django.contrib.auth.decorators import login_required
    
    class LoginToPost:
        @method_decorator(login_required)
        def post(self, arg, *args, **kwargs):
            super().post(arg, *args, **kwargs)
    

    Likewise for the other methods.

    In the inheritance list of my concrete classes, I would add my LoginToPost before ListCreateAPIView and LoginToPutOrDelete before RetrieveUpdateDestroyAPIView. My concrete classes' get would stay undecorated.

提交回复
热议问题