【发布时间】:2017-07-27 05:52:27
【问题描述】:
在许多编程语言中,父类可以要求任何子类包含特定字段。
如果字段是静态的,在Julia中可以通过以下方式达到同样的效果。
julia> abstract Fruit
julia> type Apple <: Fruit end
julia> type Orange <: Fruit end
julia> type Banana <: Fruit end
julia> color(::Apple) = :red
color (generic function with 1 method)
julia> color(::Orange) = :orange
color (generic function with 2 methods)
julia> color(::Banana) = :yellow
color (generic function with 3 methods)
但是,如果字段是动态的,这将不起作用。在以下示例中,我想要求 Pet 的任何子类型包含字段 name。
julia> abstract Pet
julia> type Cat <: Pet
name::String
hairless::Bool
end
julia> type Dog <: Pet
name::String
end
julia> abstract Bird <: Pet
julia> type Parrot <: Bird
name::String
color::Symbol
end
julia> type Conure <: Bird
name::String
end
julia> feet(::Cat) = 4
feet (generic function with 1 method)
julia> feet(::Dog) = 4
feet (generic function with 2 methods)
julia> feet(::Bird) = 2
feet (generic function with 3 methods)
类型确实必须不同,因为它们也可能具有其他属性,并且可以为每种类型唯一定义方法。
- 如何执行此要求?理想情况下,我不必在任何子类型中指定
name字段,但如果必须,就这样吧。 - 如果这在 Julia 中是不可能的,建议的替代方案是什么?我可以重构这种类型的代码以完全消除这种行为的需要吗?
【问题讨论】:
标签: types abstract-class julia abstract