如何在 Julia 中为结构创建构造函数?

log*_*ick 5 julia

我最近开始在 Julia 中做面向对象的工作,并且喜欢使用结构体(Python 相当于一个类?)。

我在这里阅读了有关结构的文档,但我没有看到有关结构中构造函数或方法的任何内容。我已经看到在一些地方使用了结构体,有人在结构体内部实际定义了一个函数。我怎么能这样做,你为什么要那样做?

Prz*_*fel 5

当您仔细阅读 StefanKarpinski 建议的文档(它非常好)时,请查看Parameters包,在我看来,它使面向对象的 Julia 转换变得更好。

看看这个代码:

@with_kw mutable struct Agent
    age = 0
    income = rand()
end

function Agent(age::Int)
    income = rand()+age*10
    Agent(age, income)
end
Run Code Online (Sandbox Code Playgroud)

现在有一些用法:

julia> Agent()
Agent
  age: Int64 0
  income: Float64 0.28109332504865625


julia> Agent(income=33)
Agent
  age: Int64 0
  income: Int64 33


julia> Agent(age=3)
Agent
  age: Int64 3
  income: Float64 0.5707873066917069


julia> Agent(30)
Agent
  age: Int64 30
  income: Float64 300.1706559468855
Run Code Online (Sandbox Code Playgroud)

最后一个构造函数是定制的,而前三个是由@withkw宏自动生成的。

最后但并非最不重要的。考虑一个循环引用数据结构,即 AgentY1 只能有 AgentY2 类型的朋友,AgentY2 只能有 AgentY1 类型的朋友:

据我所知(如果我错了,也许有人可以纠正我)这只能使用宏来实现:

@with_kw mutable struct AgentY1
    age::Int
    friends=AgentY2[]
end


@with_kw mutable struct AgentY2
    age::Int
    friends=AgentY1[]
end
Run Code Online (Sandbox Code Playgroud)

现在示例用法:

julia> aa = AgentY1(age=11)
AgentY1
  age: Int64 11
  friends: Array{AgentY2}((0,))
Run Code Online (Sandbox Code Playgroud)

这就是我在 Julia 中进行面向对象编程的方式。