如何处理 class 层次结构中的 python 装饰器?

how to deal with python decorators in a class hierarchy?

我正在使用 DRF. I also have used drf-yasg 开发一个 Django 项目用于文档目的。

长话短说:我正在使用基于 class 的视图并且我有一些非常相似的 API,我决定制作一个超级 class 并实现 API 的公共部分在里面!为了更清楚:

class MySuperApiView(APIView):
    permission_classes = [<some permission classes>]

    def uncommon(self):
        pass  # to be override in subclasses

    @swagger_auto_schema(request_body=request_body, responses=api_responses)
    def post(self, *args, **kwargs):
        # do some common stuff here
        self.uncommon()
        # do some other common stuff here

我只是重写了 child-classes:

中的 uncommon 方法
class SomeCustomApi(MySuperApiView):
    def uncommon(self):
        # do specific things here

它工作正常,但我有一个小问题:每个 Api 都有自己的 api_responses,它在 super-class 的 swagger_auto_schema 装饰器中初始化!而且无法更改!

对于这种情况,您有什么建议?好想做OOP,遵守DRY原则

我终于找到了在 Django 中做这种事情的最佳方法! (所以是的,我不知道如何在其他框架或语言中处理这样的问题!) 我使用名为 method_decorator 的 class 装饰器将 swagger_auto_schema 装饰器移动到 child-class。所以首先我必须导入这个方法:

from django.utils.decorators import method_decorator

然后我像这样更改了 super-class 和 child-class:

class MySuperApiView(APIView):
    permission_classes = [<some permission classes>]

    def uncommon(self):
        pass  # to be override in subclasses

    # <I removed decorator from here!>
    def post(self, *args, **kwargs):
        # do some common stuff here
        self.uncommon()
        # do some other common stuff here
api_responses =  # responses which belong to "SomeCustomApi"

@method_decorator(name='post',
                  decorator=swagger_auto_schema(request_body=request_body,
                                                responses=api_responses))
class SomeCustomApi(MySuperApiView):
    def uncommon(self):
        # do specific things here

它工作得很好 :) 但是我更喜欢一个解决方案,在该解决方案中我不必重复装饰器,而是只需初始化 responses 参数。如果您在其他语言中遇到此类问题并且您有其他语言的答案,请 post 您的答案。