Julia: Constructor Inlining a function inside a type

I am new to OOP. Suppose I have a Type and a function like this:

type Person name::String male::Bool age::Float64 children::Int end function describe(p::Person) println("Name: ", p.name, " Male: ", p.male) println("Age: ", p.age, " Children: ", p.children) end ted = Person("Ted",1,55,0) describe(ted) 

Is there a way to enable the description function inside this type. For example, if I enter something like this

 ted.describe() 

I would get:

 Name Ted Male true Age 55.0 Children 0 
+5
source share
2 answers

I am also new to Julia and I had the same request a few times ago.

Now I would solve your problem with the following code, thanks for help from
Understanding Object Oriented Programming in Julia - Objects-part 1 ,

I know that the anonymous fix is ​​not very fast, but I think the overhead is not so bad for the print function.

 #!/usr/bin/env julia type Person name::AbstractString male::Bool age::Float64 children::Int describe::Function function Person(name,male,age,children) this = new() this.name = name this.male = male this.age = age this.children = children # anonymous functions are not known to be fast ;-) this.describe = function() describe(this) end this end end function describe(p::Person) println("Name: ", p.name, " Male: ", p.male) println("Age: ", p.age, " Children: ", p.children) end ted = Person("Ted",1,55,0) # describe(ted) ted.describe() 

However, as 0xMB said: this is not Julia's way. But I like the method of calling chains of calls from Ruby, so I hope that the parser comes up one day to be able to easily create some alias to create such a "member function".

- Maurice

+4
source

Julia does not support this point notation. This may differ from other object-oriented languages, where methods are part of your objects, but in the Julia function, they are believed to act on data in general and therefore are not defined inside your object data.

Your example is just wonderful.

+3
source

Source: https://habr.com/ru/post/1206413/


All Articles