import json class Message: MESSAGE_TYPES = {} @classmethod def decode(cls, raw): hash = json.loads(raw) tag = hash['tag'] return cls.MESSAGE_TYPES[tag].from_hash(hash) def json(self): hash = self.to_hash() return json.dumps(self.to_hash()) def message(name): def decorate(class_decl): Message.MESSAGE_TYPES[name] = class_decl return class_decl return decorate @message('config') class InitialConfig(Message): def __init__(self, user, game): self.user = user self.game = game @classmethod def from_hash(cls, d): return cls(user=d['user'], game=d['game']) def to_hash(self): return {'user': self.user, 'game': self.game} @message('post') class Post(Message): def __init__(self, author, content): self.author = author self.content = content @classmethod def from_hash(cls, d): return cls(author=d['author'], content=d['content']) def to_hash(self): return { 'tag': 'post', 'author': self.author, 'content': self.content, }