Osk*_*ar 10 methods function julia
为什么在这种情况下方法定义的顺序不同?在我看来这没有多大意义。
julia> f() = 1
f (generic function with 1 method)
julia> f(;arg) = 1
f (generic function with 1 method)
julia> f()
ERROR: UndefKeywordError: keyword argument arg not assigned
Stacktrace:
[1] f() at ./REPL[2]:1
[2] top-level scope at REPL[3]:1
julia> f() = 1
f (generic function with 1 method)
julia> f()
1
julia> f(arg=1)
1
Run Code Online (Sandbox Code Playgroud)
由于带有关键字参数的函数如何适应 Julia 1.x 中方法分派的机制,方法定义的顺序给出了不同的结果。
正如上面的评论所指出的,简短的答案是:因为第二个定义完全覆盖了另一个定义。
但我认为这并不完全准确,让我们看看。
情况 1:订单如下:
julia> f() = 2
f (generic function with 1 method)
julia> f(;arg) = 1
f (generic function with 1 method)
julia> f()
ERROR: UndefKeywordError: keyword argument arg not assigned
Run Code Online (Sandbox Code Playgroud)
用户定义的函数f()被覆盖。
情况 2:颠倒顺序,两种方法都可见:
julia> f(;arg) = 1
f (generic function with 1 method)
julia> f() = 2
f (generic function with 1 method)
julia> f()
2
julia> f(arg=3)
1
Run Code Online (Sandbox Code Playgroud)
当f(;arg)降低时,编译器会生成不带关键字参数的方法f(),以处理未传递关键字参数的情况。
这会产生两种不同的结果:
f()覆盖用户定义的方法f()。f()方法覆盖生成的方法f(),但f(;args)仍然可见。请注意,从这两种情况来看,最终结果似乎是我们得到了一个f具有 1 个方法的函数,但实际上在第二种情况下,我们实际上有 2 个函数,每个函数有 1 个方法,一个管理用户定义的函数f(),一个管理关键字参数 version f(;arg)。
文档中详细介绍了如何降低关键字参数方法定义的完整详细信息