How about using module to simulate object with methods and data?
function Class(vars::Vector{Pair}, functions::Pair{Symbol, Function}...)
function class(me)
klass = Module(symbol(me))
varnames = [v[1] for v in vars]
self = "type that me \n" * join(varnames, "\n") * "\nend"
eval(klass, parse(self))
those = [v[2] for v in vars]
eval(klass, :(global this = that($([me; those]...))))
for func in functions
eval(klass, :($(func[1])(args...) = $(func[2])(this, args...) ))
end
return klass
end
end
Foo = Class(
Pair[
:a => 0,
:camelCounter => 0
],
:get_a => function(this)
return this.a
end,
:set_a => function(this, k)
this.camelCounter += 1
info("$(this.me): called $(this.camelCounter) times")
this.a = k
end
)
a1 = Foo("foo1")
a2 = Foo("foo2")
a1.set_a(3)
a2.set_a(4)
info("a1 = ", a1.get_a())
info("a2 = ", a2.get_a())
# INFO: foo1: called 1 times
# INFO: foo2: called 1 times
# INFO: a1 = 3
# INFO: a2 = 4
Still need to figure out how to do inheritance.
lauantai 28. marraskuuta 2015 19.19.29 UTC+2 Olli Väinölä kirjoitti:
>
> Hello!
>
> I've been using Julia for a half a year at the moment and I really like
> it. In the past I've been using mainly Python, C++ and JavaScript in which
> objects are necessary. This morning me and my friend Jukka started
> tinkering with Julia: we were wondering can you use JavaScript syntax.
> After an hour we noticed that we had created a naive object in JavaScript
> syntax. Since we had already created a object, why not use Python class
> syntax: a constructor and dot syntax for referring functions and variables.
> So, here's a funny workaround for object :)
>
> julia> type Object
> get_a
> set_a
> end
>
> julia> Object(n) = Object(() -> n["get_a"](),(m) -> n["set_a"](m))
> Object
>
> julia> Object() = Object((() -> begin
> private_data = Dict("a" => 1)
> public_data = Dict()
> methods = Dict{ASCIIString, Any}()
> methods["get_a"] = () -> private_data["a"]
> methods["set_a"] = (k) -> (private_data["a"] = k)
> methods["data"] = public_data
> methods
> end)())
> Object
>
> julia> class_1 = Object()
> Object((anonymous function),(anonymous function))
>
> julia> class_2 = Object()
> Object((anonymous function),(anonymous function))
>
> julia> class_1.get_a()
> 1
>
> julia> class_1.set_a(10)
> 10
>
> julia> class_1.get_a()
> 10
>
> not sure if someone has already invented this but in PyPlot I guess same
> has been archived with a Dict. Still, all fun and games.
>
>