Customized display of composite types in Julia

隐身守侯 提交于 2020-01-22 12:16:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!