I have recently started to do object-oriented stuff in Julia and have enjoyed using structs (the Python equivalent to a class?).
I read the documentation about structs here, but I did not see anything about constructors or methods in the struct. I have seen structs used a few places where someone actually defines a function inside of the struct. How can I do that and why would you want to do that?
When you finish reading carefully the documentation suggested by StefanKarpinski (and it is really good), have a look for the Parameters package which, in my opinion, makes the object-oriented transformation to Julia much nicer.
Have a look at this code:
@with_kw mutable struct Agent
age = 0
income = rand()
end
function Agent(age::Int)
income = rand()+age*10
Agent(age, income)
end
And now some usages:
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
The last constructor was the custom-made one, while the three previous were automatically generated by the @withkw
macro.
Last, but not least. Consider a loop reference data structure, i.e., where AgentY1 can only have friends of type AgentY2 and AgentY2 can only have friends of type AgentY1:
To my best knowledge (maybe someone can correct me if I am wrong) this can be only achieved using the macro:
@with_kw mutable struct AgentY1
age::Int
friends=AgentY2[]
end
@with_kw mutable struct AgentY2
age::Int
friends=AgentY1[]
end
And now sample usage:
julia> aa = AgentY1(age=11)
AgentY1
age: Int64 11
friends: Array{AgentY2}((0,))
This is how I do my OO programming in Julia.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With