Struct show/println/etc结构julia jupyter
我正在尝试为Julia结构创建一个专门的pretty print函数,它将以所需的方式输出到Jupyter nb。如果我只是将其中一个结构作为nb帧的结果,那么我的专门显示显然是有效的,但如果我在代码中调用show,则不行:Struct show/println/etc结构julia jupyter,struct,julia,pretty-print,Struct,Julia,Pretty Print,我正在尝试为Julia结构创建一个专门的pretty print函数,它将以所需的方式输出到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.b
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
输出(添加了#注释):
我已经尝试过很多版本——导入并覆盖Base.show,使用print和println代替show,导入/覆盖它们,等等。许多版本都是这样工作的。有些以各种可预测的方式中断,但我尝试过的组合都不允许我通过专门的fn(即,我希望A看起来像B)输出到nb流中。我相信这很简单,但我显然遗漏了一些东西您发布的代码中有两个问题:
Base
扩展show
功能,您应该明确说明:要么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çois Févotte已经回答了这个问题,但请注意,使用
参数
包获得nice结构
打印是值得的。它可能适合你的需要或不适合,但值得知道
使用此简短代码作为指导
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"
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"