【问题标题】:What is the equivalent of getattr() in Julia什么是 Julia 中的 getattr() 等价物
【发布时间】:2016-02-16 15:29:59
【问题描述】:

Julia 中 Python 的 getattr() 等价物是什么?我已经尝试过以下元编程代码,但它只能在全局范围内工作,而不是在函数范围内。

type A
  name
  value
end

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

这将打印出来:

Alex
1

但是,如果上面是在函数范围内,那么它将不起作用

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

tmp()

错误是:

ERROR: LoadError: UndefVarError: a not defined

编辑: 感谢大家回答问题。以下是 Julia 在 getfieldsetfield! 上的文档的链接。

【问题讨论】:

    标签: julia


    【解决方案1】:

    你想使用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
    

    【讨论】:

      【解决方案2】:

      您正在寻找getfield 函数:

      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>
      

      【讨论】:

      猜你喜欢
      • 2017-10-26
      • 2010-10-21
      • 2021-02-17
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 2014-06-12
      相关资源
      最近更新 更多