首页 > 解决方案 > 重载已被导入模块使用的函数名称

问题描述

我想定义一个函数

function f(a :: my_type, b :: other_args)
    ...
end

但是,我已经在使用other_module已经定义的模块f(a :: other_module_type, b :: other_args)。结果(并且显然只有在我已经使用过的情况下f(a :: other_module_type ...)),当我定义我的函数时,我得到了错误:

ERROR: error in method definition: function other_module.f must be explicitly imported to be extended

我不明白为什么仅仅因为我的函数共享相同的名称就需要扩展另一个模块。f(...)什么逻辑阻止我定义自己的other_module.f.

一个例子:

 using Dierckx
 a = Spline1D([1,2,3,4],[1,2,3,4])
 derivative(a, 1.0)
 type b end
 function derivative(c::b, x)
     return x
 end

 ERROR: error in method definition: function Dierckx.derivative must be explicitly imported to be extended

谢谢。

标签: julia

解决方案


您可以import使用模块而不是using它,以便在那里定义的名称不会进入您的范围。结果是您需要指定模块名称才能显式调用模块内的函数。

例如,您的代码应该是这样的:

import Dierckx
a = Dierckx.Spline1D([1,2,3,4],[1,2,3,4])
Dierckx.derivative(a, 1.0)
type b end
function derivative(c::b, x)
    return x
end

// now derivative() is your function, and Dierckx.derivative() calls the one in the module

背后的机制是 Julia 函数可以包含多个具有不同签名的方法( doc),因此定义一个与现有函数具有相同名称的函数本质上是对它们的扩展。为防止意外扩展不相关的函数,需要显式导入函数(如import Dierckx.derivative)进行扩展,否则会出现如您所见的错误。

对于 和 的区别importusing请参见此处


推荐阅读