Oop 朱莉娅:理解面向对象的多重分派
假设我有以下类型:Oop 朱莉娅:理解面向对象的多重分派,oop,julia,multiple-dispatch,Oop,Julia,Multiple Dispatch,假设我有以下类型: type cat cry:: String legs:: Int fur:: String end type car noise::String wheels::Int speed::Int end Lion = cat("meow", 4, "fuzzy") vw = car("honk", 4, 45) 我想给它们添加一个方法descripe,用于打印其中的数据。最好使用以下方法: describe(a::cat) = println("
type cat
cry:: String
legs:: Int
fur:: String
end
type car
noise::String
wheels::Int
speed::Int
end
Lion = cat("meow", 4, "fuzzy")
vw = car("honk", 4, 45)
我想给它们添加一个方法descripe
,用于打印其中的数据。最好使用以下方法:
describe(a::cat) = println("Type: Cat"), println("Cry:", a.cry, " Legs:",a.legs, " fur:", a.fur);
describe(a::car) = println("Type: Car"), println("Noise:", a.noise, " Wheels:", a.wheels, " Speed:", a.speed)
describe(Lion)
describe(vw)
输出:
Type: Cat
Cry:meow Legs:4 fur:fuzzy
Type: Car
Noise:honk Wheels:4 Speed:45
或者我应该使用我之前发布的问题中的函数:
哪种方法更有效
中的大多数
方法
示例都是简单的函数,如果我想要一个更复杂的方法
带有循环,或者如果可以使用语句?首先,我建议使用大写字母作为类型名称的第一个字母-这在Julia样式中是非常一致的,因此,不这样做肯定会让使用您的代码的人感到尴尬
当您使用多语句方法时,您可能应该将它们作为完整函数编写,例如
function describe(a::cat)
println("Type: Cat")
println("Cry:", a.cry, " Legs:", a.legs, " fur:", a.fur)
end
function describe(a::car)
println("Type: Car")
println("Noise:", a.noise, " Wheels:", a.wheels, " Speed:", a.speed)
end
通常,单行程序版本仅用于简单的单语句
可能还值得注意的是,我们正在使用两种方法实现一个功能,以防手册中没有明确说明
最后,您还可以向基本Julia打印函数添加一个方法,例如
function Base.print(io::IO, a::cat)
println(io, "Type: Cat")
print(io, "Cry:", a.cry, " Legs:", a.legs, " fur:", a.fur)
end
function Base.print(io::IO, a::car)
println(io, "Type: Car")
print(io, "Noise:", a.noise, " Wheels:", a.wheels, " Speed:", a.speed)
end
(如果您调用println
,它将在内部调用print
,并自动添加\n
)