Python如何覆盖在第三方库的模块中定义的方法 [英] Python how to override a method defined in a module of a third party library

查看:43
本文介绍了Python如何覆盖在第三方库的模块中定义的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过 pip 安装了第三方库 tornado 并且需要覆盖一个方法,比如在模块的全局范围内定义的to_unicode,比如tornado.escape.这样所有对该方法的调用都将使用我的覆盖版本.或者,我想控制它,以便只有我的代码将使用覆盖的版本.

如果它是在一个类中定义的,我就可以对它进行子类化并覆盖该方法!但由于这只是一个方法,我想知道如何覆盖它.

出人意料的是,我在 SO 中找到了不合适的解决方案,这是不可能实现的吗?

解决方案

您可以简单地将对象(在本例中为模块级函数)的名称重新绑定到不同的对象.例如,如果您想让 math.cos 使用度数而不是弧度,你可以这样做

<预><代码>>>>导入数学>>>math.cos(90)-0.4480736161291701>>>old_cos = math.cos>>>def new_cos(degrees):...返回 old_cos(math.radians(degrees))...>>>math.cos = new_cos>>>math.cos(90)6.123233995736766e-17

但是,这可能会导致使用该模块的其他函数出现问题...

I've installed a third party library tornado by pip and need to override a method, say to_unicode defined in the global scope of a module say tornado.escape. So that all calls to that method will use my overridden version. Or maybe, I would want to control it so that only my code will use the overridden version.

If it had been defined inside a class, I'd have no problem to subclass it and override the method! But since this is just a method, I'm wondering how to override it.

Surprisingly, I found not suitable solution in SO, is this kind of impossible to achieve?

解决方案

You can simply rebind the name of an object (in this case, a module-level function) to a different object. For example, if you want to have math.cos work with degrees instead of radians, you could do

>>> import math
>>> math.cos(90)
-0.4480736161291701
>>> old_cos = math.cos
>>> def new_cos(degrees):
...     return old_cos(math.radians(degrees))
...
>>> math.cos = new_cos
>>> math.cos(90)
6.123233995736766e-17

However, that might cause problems to other functions that use that module...

这篇关于Python如何覆盖在第三方库的模块中定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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