Julia: Understanding Multiple Submissions for OOP

Suppose I have the following types:

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)

      

And I want to add a method describe

to both of them that prints the data inside them. Your best bet is to use methods for this:

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)

      

Output:

Type: Cat
Cry:meow Legs:4 fur:fuzzy
Type: Car
Noise:honk Wheels:4 Speed:45

      

Or should I use a function like in this question I posted earlier: Julia: What is the best way to set up an OOP model for a library

Which method is more effective?

Most of the Methods

examples in the documentation are simple functions, if I need a more complex one Method

with loops or if statements are they possible?

+3


source to share


1 answer


First of all, I recommend using an uppercase letter as the first letter of the type name - this is a very tricky Julia-style thing, so not doing it will definitely be inconvenient for people using your code.

As you do multi-tasking methods, you should probably write them as complete functions, for example.

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

      

Typically, the one-liner is only used for simple single statements.



It is also worth noting that we are doing one function with two methods, if this is not clear from the manual.

Finally, you can also add a method to the basic Julia print function, for example

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

      

(if you call println

it will call print

internally and add automatically \n

)

+2


source







All Articles