Julia 中复合类型的自定义显示 [英] Customized display of composite types in Julia

查看:12
本文介绍了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 中复合类型的自定义显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆