【发布时间】:2022-02-21 18:34:46
【问题描述】:
在 Python 中,对象上的命令 dir 返回对象的属性和方法。 Julia中是否有等效的命令?我知道 Julia 没有 Python 对象意义上的方法,但是我们可以看到结构的参数吗?
【问题讨论】:
在 Python 中,对象上的命令 dir 返回对象的属性和方法。 Julia中是否有等效的命令?我知道 Julia 没有 Python 对象意义上的方法,但是我们可以看到结构的参数吗?
【问题讨论】:
如果您指的是结构的字段,则可以使用fieldnames(T) 函数获取字段名称列表,其中T 的类型为DataType。
所以说你想知道某个变量a 有哪些字段,你可以做fieldnames(typeof(a))。
【讨论】:
fieldtypes 获取字段类型。
除了fieldnames和fieldtypes,从另一个答案来看,dump函数可以用于类型和值的自省,例如
julia> struct Foo{S, T<:AbstractVector{S}}
x::T
y::Int
end
julia> dump(Foo) # <-- dump on the type
UnionAll
var: TypeVar
name: Symbol S
lb: Union{}
ub: Any
body: UnionAll
var: TypeVar
name: Symbol T
lb: Union{}
ub: AbstractArray{S, 1} <: Any
body: Foo{S, T<:AbstractArray{S, 1}} <: Any
x::T
y::Int64
julia> dump(Foo([1, 2, 3], 1)) # <-- dump on a value
Foo{Int64, Vector{Int64}}
x: Array{Int64}((3,)) [1, 2, 3]
y: Int64 1
【讨论】:
@frederikekre 的回答让我想起了 Eyeball.jl 的神奇包裹。它让您可以交互式地探索类型及其实例、获取它们的文档、对它们进行操作的方法 (methodswith) 等等。(但请注意,它的版本为 0.4.4,您可能还会遇到偶尔出现的错误。)
在这里,输入eye(fb) 后,我按下箭头一次转到r: RegexMatch,然后m 以获取接受RegexMatch 的方法列表。
julia> struct FooBar
r::RegexMatch
s::SubstitutionString
end
julia> fb = FooBar(match(r"\d+", "test123"), s"42")
FooBar(RegexMatch("123"), s"42")
julia> eye(fb)
[f] fields [d] docs [e] expand [m/M] methodswith [o] open [r] tree [s] show [t] typeof [z] summarize [q] quit
: FooBar FooBar(RegexMatch("123"), s"42")
> r: RegexMatch RegexMatch("123")
match: SubString{String} "123"
string: String "test123"
offset: Int64 4
ncodeunits: Int64 3
captures: Vector{Union{Nothing, SubString{String}}} (0,) 0 Union{Nothing, SubString{String}}[]
offset: Int64 5
offsets: Vector{Int64} (0,) 0 Int64[]
regex: Regex r"\d+"
pattern: String "\\d+"
compile_options: UInt32 0x040a0002
match_options: UInt32 0x40000000
regex: Ptr{Nothing} Ptr{Nothing} @0x00000000024163f0
s: SubstitutionString{String} s"42"
string: String "42
Opening methodswith(`r`) ...
[f] fields [d] docs [e] expand [m/M] methodswith [o] open [r] tree [s] show [t] typeof [z] summarize [q] quit
> : Vector{Method} (12,) 96 Method[FooBar(r::RegexMatch, s::SubstitutionString) in Main at REPL[25]:2, eltype(m::RegexMatch) in Bas
1: Method FooBar(r::RegexMatch, s::SubstitutionString) in Main at REPL[25]:2
2: Method eltype(m::RegexMatch) in Base at regex.jl:262
3: Method getindex(m::RegexMatch, idx::Integer) in Base at regex.jl:245
4: Method getindex(m::RegexMatch, name::AbstractString) in Base at regex.jl:251
5: Method getindex(m::RegexMatch, name::Symbol) in Base at regex.jl:246
6: Method haskey(m::RegexMatch, idx::Integer) in Base at regex.jl:253
7: Method haskey(m::RegexMatch, name::AbstractString) in Base at regex.jl:258
8: Method haskey(m::RegexMatch, name::Symbol) in Base at regex.jl:254
9: Method iterate(m::RegexMatch, args...) in Base at regex.jl:260
10: Method keys(m::RegexMatch) in Base at regex.jl:219
11: Method length(m::RegexMatch) in Base at regex.jl:261
12: Method show(io::IO, m::RegexMatch) in Base at regex.jl:227
【讨论】: