问题
Suppose you define a new composite type in Julia and a variable of that type:
type MyType
α::Int64
β::Vector{Float64}
γ::Float64
MyType(α::Int64, β::Vector{Float64}, γ::Float64) = new(α, β, γ)
end
mt = MyType(5, [1.2, 4.1, 2], 0.2)
Now if you are in REPL mode, you can simply check the value of mt
by typing mt
and pressing Enter:
mt
MyType(5,[1.2,4.1,2.0],0.2)
If I want to customize the way variables of MyType
are displayed, I can define a function and use it like customized_display(mt)
:
function customized_display(me::MyType)
println("MyType")
println("α:$(me.α), β:$(me.β), γ:$(me.γ)")
end
customized_display(mt)
MyType
α:5, β:[1.2,4.1,2.0], γ:0.2
But using another function for displaying values of mt
seems redundant. Which function do I need to extend such that by simply typing mt
, the customized display is shown?
回答1:
You should define one of the following (they will both work and have the same effect):
function Base.show(io::IO, me::MyType)
println(io, "MyType")
println(io, "α:$(me.α), β:$(me.β), γ:$(me.γ)")
end
function Base.writemime(io::IO, ::MIME"text/plain", me::MyType)
println(io, "MyType")
println(io, "α:$(me.α), β:$(me.β), γ:$(me.γ)")
end
回答2:
Note: The answer by spencerlyon2 is no longer correct as of Julia 0.5 and later.
Given your type
type MyType
α::Int64
β::Vector{Float64}
γ::Float64
end
If you want to customize the single-line display, add a method to Base.show
like this:
function Base.show(io::IO, me::MyType)
print(io, "MyType: α:", me.α, " β:", me.β, " γ:", me.γ)
end
An example of single-line display being used:
julia> [MyType(5, [1.2, 4.1, 2], 0.2)]
1-element Array{MyType,1}:
MyType: α:5 β:[1.2, 4.1, 2.0] γ:0.2
By convention, this method should not include any newlines. This is so that it displays nicely when embedded in other objects, like arrays or matrices. Typically, it's preferred to output something that could be parsed and evaluated into an object equal to the one being shown, but this is not a hard rule.
If you want to customize the multi-line display, add a method to Base.show
like this:
function Base.show(io::IO, ::MIME"text/plain", me::MyType)
println(io, "MyType")
print(io, "α:", me.α, " β:", me.β, " γ:", me.γ)
end
Note that if you do not include this method, then the single-line display will be used. The multi-line display is used at the REPL when your object is shown on its own:
julia> MyType(5, [1.2, 4.1, 2], 0.2)
MyType
α:5 β:[1.2, 4.1, 2.0] γ:0.2
By convention, the multi-line display should not print any trailing new lines.
来源:https://stackoverflow.com/questions/31536246/customized-display-of-composite-types-in-julia