本文介绍了自定义显示Julia中的复合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在Julia中定义了一个新的复合类型以及该类型的变量:

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)

现在,如果您处于REPL模式,则只需键入mt并按Enter键即可简单地检查mt的值:

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)

如果我想自定义MyType变量的显示方式,我可以定义一个函数并像customized_display(mt)一样使用它:

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

但是使用另一个函数显示mt的值似乎是多余的.我需要扩展哪个功能,以便只需键入mt即可显示自定义显示?

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?

推荐答案

您应定义以下内容中的一个 (它们将同时起作用并具有相同的效果):

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

这篇关于自定义显示Julia中的复合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 00:13