使用string()的自己类型的julia插值
我对Julia很陌生,我正在考虑向Julia移植一些Python代码。这段代码使用_repr__;()重载来显示cutsom类型。我知道Julia为这个功能提供了string()方法。但我想不出来使用string()的自己类型的julia插值,julia,Julia,我对Julia很陌生,我正在考虑向Julia移植一些Python代码。这段代码使用_repr__;()重载来显示cutsom类型。我知道Julia为这个功能提供了string()方法。但我想不出来 julia> type Thomas t::Integer end julia> function Base.string(t::Thomas) "---> $(t.t) <---" end julia>
julia> type Thomas
t::Integer
end
julia> function Base.string(t::Thomas)
"---> $(t.t) <---"
end
julia> r = Thomas(8);
我做错了什么?我是否应该为新的自定义类型定义其他函数
我正在运行Julia 0.4.0-dev(上面的代码是从0.4.0-dev+3607(2015-02-26 07:41 UTC)版本的REPL粘贴的),Commit bef6bf3*,x86_64-linux-gnu)您可能还需要覆盖
show
方法
Base.show(io::IO, x::Thomas) = show(io, string(x))
必须重写Base.print的两个版本,才能获得一致的字符串插值行为:
Base.print(io::IOBuffer, t::Thomas) = Base.print(io, "---> $(t.t) <---")
Base.print(t::Thomas) = Base.print("---> $(t.t) <---")
和co.目前,只需覆盖
Base.show
就足够了,如下所示
type Thomas
t::Int # note Int not Integer
end
Base.show(io::IO, x::Thomas) = print(io, "Thomas with $(x.t)")
请注意,在类型定义中,应使用具体类型Int
(相当于Int64
或Int32
,具体取决于机器的字长),而不是抽象类型Integer
,这将导致性能不佳
目前,
Base.show
、Base.print
等的情况确实令人困惑,但最近的一些工作(查找IOContext
)应该会很快得到简化和澄清。谢谢Vincent。似乎有几个函数:show()
,print()
,display()
等等。它们之间有什么关系?这些应该在哪里使用。它们中的一些应该产生可分析的产出吗?在Julia语言文档中,我没有找到任何关于这个主题的有用信息。感谢任何指点print
将委托给show
,因此最好像David Sanders的解决方案那样重写Base.show
。
Base.print(io::IOBuffer, t::Thomas) = Base.print(io, "---> $(t.t) <---")
Base.print(t::Thomas) = Base.print("---> $(t.t) <---")
print(t)
string(t)
string(t, t, ...)
"$t"
"t = $t"
"$t $t $t"
type Thomas
t::Int # note Int not Integer
end
Base.show(io::IO, x::Thomas) = print(io, "Thomas with $(x.t)")