Customized display of composite types in Julia

后端 未结 2 1650
北海茫月
北海茫月 2021-02-08 23:58

Suppose you define a new composite type in Julia and a variable of that type:

type MyType
  α::Int64
  β::Vector{Float64}
  γ::Float64

  MyType(α::Int64, β::Vec         


        
相关标签:
2条回答
  • 2021-02-09 00:35

    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
    
    0 讨论(0)
  • 2021-02-09 00:44

    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.

    0 讨论(0)
提交回复
热议问题