为什么在这种情况下方法定义的顺序不同?在我看来这没有多大意义。
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
最佳答案
方法定义的顺序会因为函数的不同而给出不同的结果
with 关键字参数适合 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
用户定义函数 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
当f(;arg)
降低编译器生成方法 f()
, 没有关键字参数,处理没有传递关键字参数的情况。
这会产生两种不同的结果:
f()
覆盖用户定义的 f()
. f()
覆盖生成的方法 f()
但是 f(;args)
仍然可见。 请注意,从这两种情况来看,似乎作为最终结果
我们得到一个函数
f
使用 1 个方法,但实际上在第二种情况下,我们实际上有 2 个函数,每个函数有 1 个方法,一个管理用户定义的
f()
和一个管理关键字参数版本 f(;arg)
.详细介绍了如何降低关键字参数方法定义的完整细节
在 docs
关于function - 方法定义的顺序给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65614290/