【发布时间】:2021-09-10 03:52:32
【问题描述】:
我正在尝试查看特定对象在 Julia 中具有的方法、属性等。我知道一些可能让我参与其中的选项是 fieldnames() 或 hasproperty() 但是否有一个选项可以为我提供所有属性(类似于 dir function in python)?
【问题讨论】:
标签: julia
我正在尝试查看特定对象在 Julia 中具有的方法、属性等。我知道一些可能让我参与其中的选项是 fieldnames() 或 hasproperty() 但是否有一个选项可以为我提供所有属性(类似于 dir function in python)?
【问题讨论】:
标签: julia
假设你有一个类型T。
要查看所有接受T 类型对象作为参数的方法,您可以:
methodswith(T)
查看所有字段(即:类型的“属性”):
fieldnames(T)
如果你想将所有信息组合成一个函数,你可以自己做一个,像这样:
function allinfo(type)
display(fieldnames(type))
methodswith(type)
end
如果你有一个对象a而不是一个类型,那么过程是相同的,但是用typeof(a)代替上面的T和type:
# 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)。
不完全符合您的要求,但 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"
【讨论】: