【问题标题】:Julia: Understanding Multiple dispatch for OOPJulia:了解 OOP 的多重调度
【发布时间】:2015-01-12 19:52:44
【问题描述】:

假设我有以下类型:

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 set up a OOP model for a library

哪种方法更有效?

documentation 中的大多数 Methods 示例都是简单的函数,如果我想要一个更复杂的带有循环的 Method 或 if 语句可以吗?

【问题讨论】:

    标签: oop julia multiple-dispatch


    【解决方案1】:

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

    通常单行版本仅用于简单的单个语句。

    还值得注意的是,我们正在制作一个 function,带有两个 methods,以防手册中没有明确说明。

    最后,您还可以在基础 Julia print 函数中添加一个 方法,例如

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-05
      • 2021-12-04
      • 2013-06-23
      • 2015-12-20
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多