show/println/etc 结构朱莉娅 jupyter

show/println/etc struct julia jupyter

我正在尝试为 Julia 结构创建一个专门的漂亮打印函数,它将以所需的方式输出到 Jupyter nb。如果我只是将其中一个结构作为 nb 框架的结果,那么我的专业表演显然有效,但如果我在代码中调用 show:

using Printf
struct foo
    bar
end
show(io::IO, ::MIME"text/plain", f::foo) = @printf(io, "A Foo with Bar=%s!!!",f.bar)
f1=foo(1234)
show(f1)                     # A
f1                           # B

输出(添加了 # 条评论):

foo(1234)                    # This comes from the inline show (A)
A Foo with Bar=1234!!!       # This is the result that's just blatted out from the eval (B)

我已经尝试了很多版本 -- 导入和覆盖 Base.show,使用 print 和 println 而不是 show,以及 importing/overriding 那些,等等等等。许多版本都像上面那样工作。有些以各种可预测的方式中断,但我尝试过的组合都没有让我通过我的专用 fn 输出到 nb 流(即,我希望#A 看起来像#B)。我确信这很简单,但我显然只是遗漏了一些东西

您发布的代码中存在两个问题:

  1. 为了从 Base 扩展 show 函数,您应该对其进行明确说明:import Base: show 或为 Base.show[=24 明确定义您的方法=]
  2. 虽然(作为开发人员)show 是扩展新类型的好函数,但您(作为用户)仍应使用 display 来显示值。

固定这些收益率:

using Printf
struct foo
    bar
end

# Explicitly extend Base.show to tell how foo should be displayed
Base.show(io::IO, ::MIME"text/plain", f::foo) = @printf(io, "A Foo with Bar=%s!!!",f.bar)

f1=foo(1234)

# Call display to actually display a foo
display(f1)   # -> A Foo with Bar=1234!!! (printed on stdout)
f1            # -> A Foo with Bar=1234!!! (displayed as output)

虽然@François Févotte 已经回答了这个问题,但请注意,值得使用 Parameters 包来获得漂亮的 struct 打印。它可能适合或不适合您的需要,但值得了解。

使用此短代码作为指导。

julia> using Parameters

julia> struct S1            
       x::Int               
       b::String            
       end                  
                            
julia> @with_kw struct S2   
       x::Int               
       b::String            
       end                  
S2                          
                            
julia> S1(5, "Hello")       
S1(5, "Hello")              
                            
julia> S2(5, "Hello")       
S2                          
  x: Int64 5                
  b: String "Hello"