我可以重新定义函数,但在新定义中仍使用旧定义吗?

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

背景

在我的项目中,我生成各种图形和其他二进制文件。我的目标是检测这些文件中的任何更改,而不将它们包含在 Git 中,因为它们很大。我提出的解决方案涉及添加存储校验和的伴随文件,只有这些伴随文件才会被 Git 跟踪。

示例

考虑一个场景,其中我使用假设的

Plot
包,它提供了
save(filename::String, fig::Figure)
函数。我的目标是重新定义
Plot.save
函数,使其另外保存仅包含校验和的伴随文件。

using Plot

function Plot.save(filename::String, fig::Figure)
    write(filename * ".chksum", string(hash(fig)))
    Plot.save(filename, fig) # <- PROBLEM: this line causes infinite recursion, 
                             #             I need to call the original definition
end

问题

我目前面临的问题是如何从这个新定义中调用原始的

Plot.save
函数。有办法实现吗?


更新我发现了一个非常相似的问题:https://stackoverflow.com/a/58423251/2001017

julia
1个回答
0
投票

只要函数定义在不同的模块中,并且只要您希望拦截的代码未指定模块,您就可以执行类似的操作。

一个现实世界的例子:

import Plots

function plot(args...)
    println("my plot func")
    Plots.plot(args...)
end

julia> plot([1, 2, 3])
my plot func # plot generated in window

julia> Plots.plot([1, 2, 3])
# nothing printed, plot generated in window

但是在您打算注册供公共使用的包中,这种事情可能并不可取。

© www.soinside.com 2019 - 2024. All rights reserved.