Python @classmethod
Python tip:
You can use
@classmethod
to create class methods.For example, you can create a class method that loads events from a JSON string message👇
import datetime import json class UserRegistered: def __init__(self, username, event_time): self.username = username self.event_time = event_time @classmethod def from_event_message(cls, message): message = json.loads(message) return cls( username=message["username"], event_time=datetime.datetime.fromisoformat(message["event_time"]), ) message = '{"username": "johndoe", "event_time": "2021-04-26T20:00:00"}' event = UserRegistered.from_event_message(message) print(event.username, event.event_time) # => johndoe 2021-04-26 20:00:00