Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

JSON representation of the class with an object as a class variable

I have a class that contains an instance of another class. Now I want to get JSON representation of Response class with Message class instance self.msg JSON representation too. Below that's how this could be done, but is it proper way to do so?

class Response:

def __init__(self, some_attr: str, msg: Message):
    self.some_attr = some_attr
    self.msg = msg

def __str__(self):
    copy_res_dict = self.__dict__.copy()
    copy_res_dict['msg'] = self.msg.__dict__
    return json.dumps(copy_res_dict)

res = Response(Message())
res.__str__()

Comments