julia - 重载已被导入模块使用的函数名称
问题描述
我想定义一个函数
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
谢谢。
解决方案
您可以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
)进行扩展,否则会出现如您所见的错误。
对于 和 的区别import
,using
请参见此处。
推荐阅读
- android - 转发同意 Facebook Audience Network SDK (GDPR)
- javascript - Chrome 扩展程序:URL 字段中的上下文菜单
- google-api - 我怎么知道为其他谷歌帐户的用户启用了谷歌两因素身份验证?
- php - 通过多个值在多维数组中搜索
- angular - VSCode 在 Angular 项目中找不到路径
- spartacus-storefront - 如何添加我的自定义页面解析器而不是 Spartacus 页面解析器?
- fortran - Fortran 中的非表格数据结构
- javascript - 通过 Nunjucks Templating 在 json 对象中添加数据
- terraform - 本地测试不影响后端
- c# - 如何在不更改 url 的情况下调用 asp.net mvc 操作