3

可以说我有以下类型:

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)

我想为它们添加一个方法describe来打印它们内部的数据。最好使用方法来做到这一点:

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: What is the best way to setup a OOP model for a library

哪种方法更有效?

文档中的大多数Methods示例都是简单的函数,如果我想要更复杂的循环或 if 语句是否可能?Method

4

1 回答 1

4

首先,我建议使用大写字母作为类型名称的第一个字母——这在 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自动添加)

于 2014-11-15T17:06:47.547 回答