Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of getattr() in Julia

Tags:

julia

What is the equivalent of Python's getattr() in Julia? I have tried the following meta-programming code, but it only works at the global scope, not inside a function scope.

type A
  name
  value
end

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

This will print out:

Alex
1

However, if the above is inside a function scope, then it won't work

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

tmp()

The error is:

ERROR: LoadError: UndefVarError: a not defined

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

like image 668
Steven Avatar asked Feb 16 '16 15:02

Steven


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
like image 87
mbauman Avatar answered Oct 21 '22 01:10

mbauman


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>
like image 28
HarmonicaMuse Avatar answered Oct 21 '22 03:10

HarmonicaMuse