微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

show / println / etc struct julia 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,然后导入/覆盖这些,依此类推。许多版本都可以像上面那样工作。以各种可预测的方式进行了一些中断,但是我尝试过的任何组合都无法让我通过专用的fn输出到nb流中(即,我希望#A看起来像#B)。我敢肯定这很简单,但是显然我只是想念一些东西

解决方法

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

  1. 为了从show扩展Base函数,您应该对此明确:import Base: show或为Base.show明确定义方法
  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çoisFé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"         
                            

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。