Access attribute (field) using symbol (or string)

44 views
Skip to first unread message

Femto Trader

unread,
May 31, 2016, 2:54:02 PM5/31/16
to julia-users
Hello,

I have a type like

type V
    x::Float64
    y::Float64
    z::Float64
end

v = V(1.0,2.0,3.0)

that
fieldnames(v)
returns attributes of v as symbol

I would like to access to field x using either :x symbol (or "x" string)

I tried

get(v, :x)

but it raises
ERROR: MethodError: `get` has no method matching get(::V, ::Symbol)
Closest candidates are:
  get(::ObjectIdDict, ::ANY, ::ANY)
  get{K,V}(::Dict{K,V}, ::Any, ::Any)
  get{K}(::WeakKeyDict{K,V}, ::Any, ::Any)
  ...


Any idea ?

Kind regard


PS: here is the context of such a question https://github.com/JuliaStats/DataFrames.jl/issues/982

using DataFrames
a_V = [V(1.0,2.0,3.0), V(4.0,5.0,6.0)]
println(a_V)
df = DataFrame(myvar=a_V)
│ Row │ myvar          │
├─────┼────────────────┤
│ 1   │ V(1.0,2.0,3.0) │
│ 2   │ V(4.0,5.0,6.0) │

# I'd prefer to have x, y, z as column

df2 = DataFrame()
#df2[:x] = map((val)->val.x, a_V)
#df2[:y] = map((val)->val.y, a_V)
#df2[:z] = map((val)->val.z, a_V)
for fieldname in fieldnames(V)
    df2[fieldname] = map((val)->val.x, a_V)
end
println(df2)

Yichao Yu

unread,
May 31, 2016, 2:55:48 PM5/31/16
to Julia Users


On May 31, 2016 2:54 PM, "Femto Trader" <femto....@gmail.com> wrote:
>
> Hello,
>
> I have a type like
>
> type V
>     x::Float64
>     y::Float64
>     z::Float64
> end
>
> v = V(1.0,2.0,3.0)
>
> I read on http://docs.julialang.org/en/release-0.4/devdocs/reflection/
> that
> fieldnames(v)
> returns attributes of v as symbol
>
> I would like to access to field x using either :x symbol (or "x" string)
>
> I tried
>
> get(v, :x)

getfield

Femto Trader

unread,
May 31, 2016, 2:58:48 PM5/31/16
to julia-users
I got it

getfield(v, :x)

Sorry
Reply all
Reply to author
Forward
0 new messages