【问题标题】:Get all object attributes in Julia?获取 Julia 中的所有对象属性?
【发布时间】:2021-09-10 03:52:32
【问题描述】:

我正在尝试查看特定对象在 Julia 中具有的方法、属性等。我知道一些可能让我参与其中的选项是 fieldnames()hasproperty() 但是否有一个选项可以为我提供所有属性(类似于 dir function in python)?

【问题讨论】:

    标签: julia


    【解决方案1】:

    从一个类型中检索所有属性

    假设你有一个类型T

    要查看所有接受T 类型对象作为参数的方法,您可以:

    methodswith(T)
    

    查看所有字段(即:类型的“属性”):

    fieldnames(T)
    

    如果你想将所有信息组合成一个函数,你可以自己做一个,像这样:

    function allinfo(type)
       display(fieldnames(type))
       methodswith(type)
    end
    

    检索对象的所有属性

    如果你有一个对象a而不是一个类型,那么过程是相同的,但是用typeof(a)代替上面的Ttype

    # See all methods
    methodswith(typeof(a))
    
    # See all fields
    methodswith(typeof(a))
    
    # Function combining both
    function allinfo(a)
       type = typeof(a)
       display(fieldnames(type))
       methodswith(type)
    end
    

    检索所有属性,无论其性质如何

    使用多重分派,您可以定义一个具有三种方法的函数,无论您作为参数传递什么,都可以获取所有信息。

    如果您想要检查接受 Type 对象作为参数的方法,则需要第三种情况。

    # Gets all info when argument is a Type
    function allinfo(type::Type)
       display(fieldnames(type))
       methodswith(type)
    end
    
    # Gets all info when the argument is an object
    function allinfo(a)
       type = typeof(a)
       display(fieldnames(type))
       methodswith(type)
    end
    
    # Gets all info when the argument is a parametric type of Type
    function allinfo(a::Type{T}) where T <: Type
       methodswith(a)
    end
    

    【讨论】:

    • 如果我想传入一个实际的对象,比如a = [1,2],然后获取a 本身的信息,而不一定是类型?
    • 在函数顶部添加type = typeof(a)并将函数签名更改为allinfo(a)
    【解决方案2】:

    不完全符合您的要求,但 dump 非常方便

    julia> struct A
               a
               b
           end
    
    julia> dump(A((1,2),"abc"))
    A
      a: Tuple{Int64, Int64}
        1: Int64 1
        2: Int64 2
      b: String "abc"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-20
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 2011-10-16
      相关资源
      最近更新 更多