Skip to content

Instantly share code, notes, and snippets.

@s3cur3
Last active Sep 9, 2021
Embed
What would you like to do?
Elixir GenServer versus Python class
my_user = User.start_link("Tyler", "abcd-efgh-1234-5678")
# Prints "Hi, I'm Tyler"
User.say_hello(my_user)
# Prints a process ID
IO.inspect(my_user)
# Prints the state data:
# %{name: "Tyler", id: "abcd-efgh-1234-5678"}
IO.inspect(:sys.get_state(my_user))
# Hi, I'm Tyler Young
User.update_name(my_user, "Tyler Young")
User.say_hello(my_user)
my_user = User("Tyler", "abcd-efgh-1234-5678")
# Prints "Hi, I'm Tyler"
my_user.say_hello()
# Prints a memory address:
# <__main__.User object at 0x103e4aeb0>
print(my_user)
# Prints the data:
# {'name': 'Tyler', 'id': 'abcd-efgh-1234-5678'}
print(my_user.__dict__)
# Hi, I'm Tyler Young
my_user.set_name("Tyler Young")
my_user.say_hello()
defmodule User do
use GenServer
def start_link(user_name, user_id, opts \\ []) do
server_name = Keyword.get(opts, :name, __MODULE__)
GenServer.start_link(__MODULE__, %{name: user_name, id: user_id}, name: server_name)
end
def update_name(server, new_name), do: GenServer.call(server, {:set_name, new_name})
def say_hello(server), do: GenServer.call(server, :say_hello)
@impl GenServer
def init(state), do: {:ok, state}
@impl GenServer
def handle_call({:set_name, new_name}, _from, state) do
{:reply, new_name, %{state | name: new_name}}
end
@impl GenServer
def handle_call(:say_hello, _from, %{name: name} = state) do
IO.puts("Hi, I'm #{name}")
{:reply, :ok, state}
end
end
class User:
def __init__(self, name, id):
self.name = name
self.id = id
def say_hello(self):
print(f"Hi, I'm {self.name}")
def set_name(self, new_name):
self.name = new_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment