julia - Julia:如何为新的数组类型编写 repl 的打印方法?
问题描述
抱歉,代码有点长,但它是 MWE。
比如说,我定义了一个模块,它定义了一个新的向量类型,称为CmpVector
. 我想覆盖打印到回购的文本。所以我已经覆盖、打印、显示和显示,但它仍然打印自己的东西。如何将打印重载到 REPL 以获取新数组?
module CmpVectors
import Base:size,print,show,getindex, setindex!, display
mutable struct CmpVector{T} <: AbstractVector{T}
# compressed::Vector{UInt8}
# vector_pointer::Ptr{T}
inited::Bool
# size::Tuple
end
size(pf::CmpVector{T}) where T = (1,)
display(io::IO, pf::CmpVector{T}) where T = begin
if pf.inited
display(io, "NOO")
else
display(io, "Vector in compressed state")
end
end
show(io::IO, pf::CmpVector{T}) where T = begin
if pf.inited
show(io, "NOO")
else
show(io, "Vector in compressed state")
end
end
print(io::IO, pf::CmpVector{T}) where T = begin
if pf.inited
show(io, "NOO")
else
print(io, "Vector in compressed state")
end
end
getindex(pf::CmpVector{T}, i...) where T = zero(T)
end # module
我跑了这个
using Revise
using CmpVectors
CmpVectors.CmpVector{Int}(true)
它打印
1-element CmpVectors.CmpVector{Int64}:
0
解决方案
您希望重载( )show
中的 which ,而不是定义您自己的. 此外,您应该指定要重载的 MIME 类型。Base
Base.show
show
mutable struct MyType
val::Symbol
end
function Base.show(io::IO, ::MIME"text/plain", mytype::MyType)
println(io, "This is my type which contains $(mytype.val)")
end
MyType(:something)
## outputs
This is my type which contains something
推荐阅读
- php - Chrome 未向服务器提交 POST 请求
- active-directory - 如何转义 LDAP dn 进行查找?
- python - 在 while 循环中更新 Render_template
- python - 将 spark 转换为 pandas 数据框有异常:使用基于文件的收集时不支持箭头
- go - 并行获取多个字段的模式
- javascript - jQuery Slick Slider:如何滚动不到一整张幻灯片
- web-scraping - 在 python 3.6 中使用 beautifulsoup4 抓取网站以获取产品信息
- python - Python -- 值错误:索引 968 处不支持的格式字符 ',' (0x2c)
- php - 链接到外部站点时出现相对 url 的问题
- docker - OCI 运行时失败 container_linux:345 启动容器进程导致 process_linux init 导致 rootfs_linux:58 挂载导致 perm 拒绝未知