我正在尝试查看Julia中特定对象的方法、属性等。我知道一些选项可能会让我参与其中,比如fieldnames()
或hasproperty()
,但有没有一个选项会让我所有属性(类似于python中的dir
函数(?
从类型检索所有属性
假设您有一个类型T
。
要查看所有接受T
类型对象作为参数的方法,可以执行以下操作:
methodswith(T)
要查看所有字段(即:类型的"属性"(:
fieldnames(T)
如果你想把所有信息组合成一个函数,你可以自己做一个,比如:
function allinfo(type)
display(fieldnames(type))
methodswith(type)
end
检索对象的所有属性
如果不是有一个Type,而是有一个对象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
不是你想要的,但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"