ErlPort allows you to work with Python and Ruby code from Elixir.
However, there was no description about the class in Documentation, so I actually tried it.
From the conclusion, it behaves a little counter-intuitive.
$ mix new python
python/mix.exs
defmodule Python.Mixfile do
# ...
defp deps do
[
{:erlport, github: "hdima/erlport"}
]
end
end
python/sample.py
class Sample(object):
def __init__(self):
print("Sample.__init__")
self.message = "Hello, world!"
def print_message(self):
print(self.message)
def set_message(self, msg):
self.message = msg
Start the python process with : python.start ()
and call the function with : python.call ()
.
$ iex -S mix
iex(7)> {:ok, python} = :python.start([python_path: '.'])
iex(8)> obj = python |> :python.call(:sample, :Sample, [])
Sample.__init__
iex(9)> python |> :python.call(:sample, :"Sample.print_message", [obj])
Hello, world!
There is no problem so far. Next, try calling Sample.set_message ()
.
iex(13)> python |> :python.call(:sample, :"Sample.set_message", [obj, "Hello, ErlPort!"])
iex(14)> python |> :python.call(:sample, :"Sample.print_message", [obj])
Hello, world!
that? The message hasn't changed.
If you try to return self
withSample.set_message ()
and let the caller receive it,
python/sample.py
class Sample(object):
# ...
def set_message(self, msg):
self.message = msg
return self
iex(15)> {:ok, python} = :python.start([python_path: '.'])
iex(16)> obj = python |> :python.call(:sample, :Sample, [])
Sample.__init__
iex(18)> obj = python |> :python.call(:sample, :"Sample.set_message", [obj, "Hello, ErlPort!"])
iex(19)> python |> :python.call(:sample, :"Sample.print_message", [obj])
Hello, ErlPort!
:undefined
This time the message has changed.
It behaves as if self
is an immutable object.
Recommended Posts