重写 pip 模块的 python 类方法以全局更新其行为

问题描述 投票:0回答:0

使用 OOP 我想做类似的事情

from django.contrib import admin

class NavigateFormAdmin(admin.ModelAdmin):
    def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
        context['next_record_id'] = custom_function_to_calculate(context['obj'].id)
        res = super().render_change_form(request, context, add, change, form_url)
        return res

并且期望每当调用

render_change_form
admin.ModelAdmin
时,它应该首先调用我的重写方法(上面),然后调用原始(父)方法。但这没有什么区别,因为我的重写方法永远不会被调用,而是在对
render_change_form
的任何调用中调用原始类
admin.ModelAdmin
中的方法。


使用不需要的猴子补丁

我能够通过将以下代码添加到我的项目/服务执行开始时由解释器读取的任何 py 文件来实现我需要的东西

from django.contrib import admin
from django.template.response import TemplateResponse
# and also all the other imports used in original medthod

class NavigateFormAdmin(admin.ModelAdmin):
    def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
        opts = self.model._meta
        app_label = opts.app_label
        preserved_filters = self.get_preserved_filters(request)

        # and all the code of existing function has to be repeated here

        context['next_record_id'] = custom_function_to_calculate(context['obj'].id)

        res = TemplateResponse(request, form_template, context)
        return res

admin.ModelAdmin.render_change_form = NavigateFormAdmin.render_change_form

现在每次调用

admin.ModelAdmin.render_change_form
off-course
NavigateFormAdmin.render_change_form
被执行

但我需要在这里使用

super()
(第一段代码不起作用)因为OOP意味着可重用性,所以我能实现的并不令人满意,因为重复了原始方法的所有50行代码只有一行用于覆盖。此外,此重复代码会导致
admin.ModelAdmin

更改版本的一些意外结果
python django oop overriding monkeypatching
© www.soinside.com 2019 - 2024. All rights reserved.