python - 替换 Python 中的所有函数调用

标签 python

我正在处理一段如下所示的代码:

# This code is not modifiable

from package import distance as dist

class A:
    def calculate(self):
        ...
        # call to dist()
        ...

我的代码:

from package import A

a = A()
a.calculate()

如您所见,distance() 函数被导入到代码的顶部。 A 类调用了一个distance() 函数。它在多个地方这样做,而不仅仅是在 calculate() 中。

我希望类(class)使用我的自定义距离函数。但是,该类不允许我在构造函数中传递它,我无法修改 A 的代码。我该怎么做?这可以通过子类化吗?我尝试了以下方法,但没有用:

from package import A

class B(A):
    def __init__(self):
        from mypackage import mydistance as dist
        return super().__init__()

b = B()
b.calculate()

最佳答案

您可以使用 mock.patch功能如下:

距离.py:

def distance():
    print('distance called')

我的距离.py:

def mydistance():
    print('mydistance called')

a.py:

from distance import distance as dist


class A:
    def calculate(self):
        dist()

主要.py:

from unittest import mock

from a import A
from mydistance import mydistance


class B(A):
    def calculate(self):
        with mock.patch('a.dist', wraps=mydistance):
            super().calculate()


if __name__ == '__main__':
    b = B()
    b.calculate()

输出是:

mydistance called

根据您的用例,您可能希望将 with 语句放在其他地方(例如调用站点)。例如:

if __name__ == '__main__':
    b = B()
    with mock.patch('a.dist', wraps=mydistance):
        for _ in range(0, 100):
            b.calculate()

打补丁会产生一些开销。另一种解决方案(基本上与 oetoni 建议的相同)是重新分配属性(记住 import a):

if __name__ == '__main__':
    b = B()
    old_dist = a.dist
    a.dist = mydistance
    for _ in range(0, 100):
        b.calculate()
    a.dist = old_dist

关于python - 替换 Python 中的所有函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47237056/

相关文章:

python - Heroku 上的全文搜索、数据库和/或索引器选择?

Python递归——如何提前退出

python - TKinter:我可以设置子菜单的样式使其看起来像普通菜单吗

python - Matplotlib:开箱即用的面板标签,位于ylabel上方

python - 使用 Pyinstaller 2.0、PySide 1.1.2 绑定(bind)和 Qt 4.8 时如何在应用程序中包含图标

python - 值错误 : Too many dimensions: 3 > 2

python - 日志中的文件不可访问错误 (setuptools)

python - 'unicode' 对象没有属性 'prettify'

python - 在极坐标中显示

python - 一段时间后 POSTGIS 插入变慢