Which is equivalent to getattr () in Julia

What is the Python equivalent of getattr () in Julia? I tried the following metaprogramming code, but it only works in the global area, not inside the function area.

type A name value end a = A("Alex",1) for field in fieldnames(a) println(eval(:(a.$field))) end 

This will print:

 Alex 1 

However, if the above is within the scope of the function, then this will not work

 function tmp() a = A("Alex",1) for field in fieldnames(a) println(eval(:(a.$field))) end end tmp() 

Error:

 ERROR: LoadError: UndefVarError: a not defined 

EDIT: Thanks to everyone for answering the question. Here are links to Julia documentation on getfield and setfield! .

+6
source share
2 answers

You want to use getfield .

 julia> function tmp() a = A("Alex",1) for field in fieldnames(a) println(getfield(a, field)) end end tmp (generic function with 1 method) julia> tmp() Alex 1 
+10
source

You are looking for the getfield function:

 julia> type A name value end julia> function foo() a = A("Alex", 1) for field in fieldnames(a) @show getfield(a, field) end end foo (generic function with 1 method) julia> foo() getfield(a,field) = "Alex" getfield(a,field) = 1 julia> 
+7
source

All Articles