覆盖Django模块类方法 [英] Override Django module class method

查看:98
本文介绍了覆盖Django模块类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django应用程序中,我通过 pip 安装了一个模块。我需要覆盖位于 site-packages / module / views.py 中的某些方法。我想,我需要将此模块导入我的自定义模块目录中,并简单地继承类和重写方法。

In my Django application I have a module installed via pip. I need to override some method located in site-packages/module/views.py. I assume, I need to import this module in my custom modules directory, and simply inherit class and override method.

最好的方法是什么?如何在没有在 site-packages 目录中编写代码的情况下正确地做到这一点?

What is the best approach? How can I do it correctly without writing code in site-packages directory?

推荐答案

您追求的目标通常称为猴子补丁

What you are after is often referred to as monkey patching.

import some_module

def my_method(self):
   pass

some_module.SomeClass.a_method = my_method

请注意,尽管取决于方法的性质和库的初始化,可能也是如此后期修补方法。例如,如果要在模块加载时调用要修补的方法,则在调用它之前将永远无法对其进行修补。

Be careful though depending on the nature of the method and library initialization it may be too late to patch the method. For example if a method that you would like to patch is invoke as the module is loaded you will never be able to patch it before it is called.

尝试并修补在您的应用程序启动时尽早解决问题类

Try and patch the class in question as early as possible in your application startup

这篇关于覆盖Django模块类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆