types - Julia v0.6 构造函数和“new”关键字
问题描述
我对 Julia 中的参数复合类型(结构)感到非常困惑。我正在使用 v0.6。我想知道是否有人可以向我解释这两个代码之间的区别?第一个似乎有效,但第二个给出错误(ERROR: LoadError: syntax: too few type parameters specified in "new{...}"
)。我特别困惑:
- 例如
Point{G}(x,y) where {G<:Integer} = new(55,y)
,在第一个点定义中是什么。好像没有方法?稍后看println(methods(Point))
几行。它是“构造函数”吗?如果是这样,那么构造函数和方法之间的区别是什么? - 关键字的
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)
`
解决方案
我认为您应该阅读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
,即始终设置x
为55
. 然后new(55,y)
实际上用and创建了一个Point{G}
对象。(请注意,如果您要编写,我们将有一个循环,因此确实需要类似的东西。)从技术上讲,您应该使用来创建对象,但 Julia 足够聪明,可以自动获取x=55
y=y
Point{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 有更多技术知识的人可以给出更准确的答案。但在那之前,我希望这会有所帮助。
推荐阅读
- sql-server - 如何找到我的程序中没有调用 sql server 中的哪些 sql 类型?
- powershell - 如何将哈希表的输出转换为 CSV
- html - 如何使用 [(ngModel)] 在选择下拉列表中显示标签
- html - 在 html 元素上定位制表键“突出显示”事件的正确方法是什么?
- wpf - 如何根据启用和禁用状态在按钮单击时播放不同的声音
- vb.net - VB.NET 将对象转换为 JSON
- apache-flink - Flink SQL:将 Bigint 转换为 Timesamp
- php - PHP循环使用来自sqldb的数据的变量
- java - WorkManager 一次执行 enqueueUniquePeriodicWork() 多次?
- javascript - 为什么 Leaflet 的 choroplet 教程地图在手机上不起作用?