Function 方法定义的顺序给出了不同的结果

Function 方法定义的顺序给出了不同的结果,function,methods,julia,Function,Methods,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

为什么在这种情况下方法定义的顺序不同?在我看来,这没有多大意义

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()
,不带关键字参数, 处理没有传递关键字参数的情况

这会产生两种不同的结果:

  • 案例1:生成的方法
    f()
    覆盖用户定义的
    f()
  • 案例2:用户定义的
    f()
    覆盖生成的方法
    f()
    ,但
    f(;args)
    仍然可见
请注意,从这两种情况来看,最终结果似乎是 我们用一种方法得到一个函数
f
,但实际上在第二种情况下,我们有两个函数,每个函数有一种方法, 一个管理用户定义的
f()
和一个管理关键字参数版本
f(;arg)

本文详细介绍了如何降低关键字参数方法定义

中,您将遇到。这里的预期行为是一个完全覆盖另一个,因此在非交互式使用中通常不会发生这种情况。此外,请参见Simeon,您可能应该将您的注释提升为答案,因为它是一个答案。这是一个错误/功能,取决于您的观点,在2.0中可能会得到修复/更改,但在1.x中不太可能更改,因为它可能会破坏很多代码。我同意,这是一个答案。