Julia中类的方法的多重调度

abe*_*ysh 5 overloading multiple-dispatch julia

我的问题是我怎么可以重载某些方法的朱莉娅一定的阶级?

换句话说,假设我有一个类的以下定义:

type Sometype
    prop::String

    setValue::Function

    # constructor
    function Sometype()
        this = new ()

        this.prop = ""

####### v1 #######
        this.setValue = function(v::Real)
            println("Scalar Version was Invoked!")
            # operations on scalar...
            # ...
        end

####### v2 #######
        this.setValue = function(v::Vector{Real})
            println("Vector Version was Invoked!")
            # operations on vector...
            # ...
        end

####### v3 #######
        this.setValue = function(v::Matrix{Real})
            println("Matrix Version was Invoked!")
            # operations on Matrix...
            # ...
        end

        return this
    end
end
Run Code Online (Sandbox Code Playgroud)

所以当我在我的主要代码中说:

st = Sometype()
st.setValue(val)
Run Code Online (Sandbox Code Playgroud)

根据是否val标量,向量矩阵,它将调用方法的相应版本setvalue.现在,根据上面的定义,它会覆盖setvalue最后一个的定义(在本例中为矩阵版本).

Dav*_*ers 9

在Julia中不使用这种面向对象编程(OOP)的方式,其中函数存在于对象内部.

相反,在Julia中,我们只定义对象定义之外的方法.例如:

type Sometype
    prop::String
end

Sometype(v::Real) = ...

function Sometype{T}(v::Vector{T})  # parametric type
    ....
end
Run Code Online (Sandbox Code Playgroud)

请注意,第一个定义是在单行上定义简单函数的简便方法的示例,第二个示例是用于更复杂的函数.

正如@GnimucKey指出的那样v::Vector{Real},你应该使用v::Vector{T}参数化的函数来代替T.我已相应地改变了我的答案.指定为参数v::Vector{Real}从未匹配参数,这是因为不可能创建抽象类型的对象Real,和类型的不变性是指像的对象Vector{Float64}不是的子类型Vector{Real}.

  • 我认为`函数Sometype {T <:Real}(v :: Vector {T})... end`更好.因为`Vector {Int} <:Vector {Real}`将返回一个`false`,这很容易出现意外错误. (5认同)