Julia 重载已被导入模块使用的函数名
我想定义一个函数Julia 重载已被导入模块使用的函数名,julia,Julia,我想定义一个函数 function f(a :: my_type, b :: other_args) ... end 但是,我已经在使用一个模块other\u module,它已经定义了f(a::other\u module\u type,b::other\u args)。因此(显然只有在我已经使用了f(a::other_module_type…)的情况下),当我定义我的函数时,我会得到以下错误: ERROR: error in method definition: function
function f(a :: my_type, b :: other_args)
...
end
但是,我已经在使用一个模块other\u module
,它已经定义了f(a::other\u module\u type,b::other\u args)
。因此(显然只有在我已经使用了f(a::other_module_type…
)的情况下),当我定义我的函数时,我会得到以下错误:
ERROR: error in method definition: function other_module.f must be explicitly imported to be extended
我不明白为什么仅仅因为我的函数共享相同的名称就有必要扩展另一个模块。是什么逻辑阻止我定义自己版本的f(…)
,以及如何避免像扩展其他模块.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
谢谢。您可以
导入
模块,而不是使用
模块,这样定义的名称就不会进入您的范围。结果是您需要指定模块名称以显式调用模块内的函数
例如,您的代码应该如下所示:
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函数可以包含多个具有不同签名()的方法,因此定义一个与现有方法同名的函数实际上是对它们的扩展。为了防止意外扩展不相关的函数,需要显式导入函数(如import Dierckx.derivative
)以进行扩展,否则会发生错误,如您所见
有关导入和使用导入的区别,请参阅。可能重复