首页 > 解决方案 > Julia v0.6 构造函数和“new”关键字

问题描述

我对 Julia 中的参数复合类型(结构)感到非常困惑。我正在使用 v0.6。我想知道是否有人可以向我解释这两个代码之间的区别?第一个似乎有效,但第二个给出错误(ERROR: LoadError: syntax: too few type parameters specified in "new{...}")。我特别困惑:

`

workspace()
println("\nSTART")

struct Point{T<:Real}
    x::T
    y::T
    # These are not 'methods' - see below. What are they!?
    Point{G}(x,y) where {G<:Integer} = new(55,y)
    Point{H}(x,y) where {H<:AbstractFloat} = new(x, 11)
end
println(methods(Point)) # Interesting!!!

# Are these methods? Are they 'constructors'?
Point(x::T, y::T) where {T<:Integer} = Point{T}(x,y)
Point(x::T, y::T) where {T<:AbstractFloat} = Point{T}(x,y)
println(methods(Point))

p = Point(2,3)
p2 = Point(2.0,3.0)

##########################################################################

# Errors!
workspace()
println("")

struct Point{T<:Real}
    x::T
    y::T
    Point(x::T, y::T) where {T<:Integer} = new(55, y)
    Point(x::T, y::T) where {T<:AbstractFloat} = new(x, 11)
end
println(methods(Point))

p = Point(2,3)
p2 = Point(2.0,3.0)

`

标签: typesjulia

解决方案


我认为您应该阅读Julia 文档的这一部分

对您的问题的简短回答:

1) 方法可以做任何事情。构造函数创建一个对象。(如果你愿意,这是一种特殊的方法)

2) 它用于在类型定义中创建对象。

3) 使用new{T}(55,y)代替new(55,y)

第一个案例

Point{G}(x,y) where {G<:Integer} = new(55,y)在第一种情况下是一个内部构造函数。内部,因为它位于类型定义的内部。构造函数始终存在,即即使您注释掉这些行,您仍然可以这样做Point{Int64}(3,2)。因此,您实际上所做的是通过明确告诉 Julia 针对特定情况做什么来覆盖默认构造函数G<:Integer,即始终设置x55. 然后new(55,y)实际上用and创建了一个Point{G}对象。(请注意,如果您要编写,我们将有一个循环,因此确实需要类似的东西。)从技术上讲,您应该使用来创建对象,但 Julia 足够聪明,可以自动获取x=55y=yPoint{G}(x,y) where {G<:Integer} = Point{G}(55,y)new()new{G}(55,y)Point{G}G来自 lhs 上的构造函数。这将是案例 2 中的一个问题。

的输出

julia> println(methods(Point)) # Interesting!!!
# 1 method for generic function "(::Type)":
(::Type{T})(arg) where T in Base at sysimg.jl:77

告诉您,您可以通过将类型名称(包括类型参数)作为函数名称来调用构造函数,例如Point{Float64}(1.2, 3.4). 我不知道为什么 Julia 没有明确列出不同的构造函数。

# Are these methods? Are they 'constructors'?
Point(x::T, y::T) where {T<:Integer} = Point{T}(x,y)
Point(x::T, y::T) where {T<:AbstractFloat} = Point{T}(x,y)
println(methods(Point))

这些是方法。一个迹象是你可以用不同的方式命名它们:create_a_point(x::T, y::T) where {T<:Integer} = Point{T}(x,y). 对于(内部)构造函数,您不能这样做。但是,有时它们被称为“构造方法”。

第二种情况

您必须明确指定类型参数:new{T}(55,y). 与案例 1 不同的是,在 lhs 上没有给出 Julia 可以自动使用的类型参数。

也许对 Julia 有更多技术知识的人可以给出更准确的答案。但在那之前,我希望这会有所帮助。


推荐阅读