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!.
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
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>
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