Julia中类方法的多分派
我的问题是如何在Julia的某个类中重载某个方法 换句话说,假设我对一个类有如下定义:Julia中类方法的多分派,julia,overloading,multiple-dispatch,Julia,Overloading,Multiple Dispatch,我的问题是如何在Julia的某个类中重载某个方法 换句话说,假设我对一个类有如下定义: type Sometype prop::String setValue::Function # constructor function Sometype() this = new () this.prop = "" ####### v1 ####### this.setValue = function(v::Real)
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
所以当我在我的主代码中说:
st = Sometype()
st.setValue(val)
根据
val
是否为标量、向量或矩阵,它将调用相应版本的设置值
方法。现在,对于上面的定义,它用最后一个(本例中为矩阵版本)覆盖了setvalue
的定义。这种面向对象编程(OOP)风格,其中函数位于对象内部,在Julia中没有使用
相反,在Julia中,我们只是在对象定义之外定义方法。例如:
type Sometype
prop::String
end
Sometype(v::Real) = ...
function Sometype{T}(v::Vector{T}) # parametric type
....
end
请注意,第一个定义是在一行上定义简单函数的简捷方法的示例,第二个示例用于更复杂的函数
正如@GnimucKey所指出的,您应该使用函数参数为
T
的v::Vector{Real}
,而不是v::Vector{T}
。我相应地改变了我的答案。指定为v::Vector{Real}
的参数永远不会与参数匹配,因为不可能创建抽象类型Real
的对象,并且类型的不变性意味着像Vector{Float64}
这样的对象不是Vector{Real}的子类型
setValue
是一个类型为Function
的变量,可以像其他常见变量一样重写。现在看来,匿名函数
似乎需要多次分派。它覆盖setValue
这一事实就是这里的问题。我想以这样的方式对它进行编码,它将编译所有版本的setValue
,其中一个版本将被适当地调用为传递的输入类型val
,您可以使用通用函数
,尝试为这些函数赋予相同的名称,例如函数foo(v::Real)
,函数foo(v::Vector{Real}
,函数foo(v::Matrix{Real})
。然而,这不是朱莉娅风格,请看@David的回答我认为函数的某种类型{t@GnimucKey的行为是的,你说得对,很好。我会改变我的答案。