问题描述
我正在尝试为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)。我敢肯定这很简单,但是显然我只是想念一些东西
解决方法
您发布的代码中有两个问题:
- 为了从
show
扩展Base
函数,您应该对此明确:import Base: show
或为Base.show
明确定义方法 - (作为开发人员)
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"