L
L
LXSTVAYNE2021-06-06 16:31:17
Python
LXSTVAYNE, 2021-06-06 16:31:17

Json representation of a class when passed to a Python method?

In general, I would like that when passing a class to some function, it turns into json. For example, I have a Test class and when passed to requests.get(url=url, data=Test), Test turned into a json object. Is this possible or is it necessary to manually call __repr__() or __str__() on the class ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WolfInChains, 2021-06-06
@lxstvayne

https://ru.stackoverflow.com/questions/710090/clas...

V
Vindicar, 2021-06-06
@Vindicar

It's much better to explicitly add the to_json() method to your class, and call it explicitly.
It will be much easier to implement and understand.
__str__() is for a human-readable representation, and __repr__() is ideally for a string representation that can be eval'ed back into an object.
They do not fit well under serialization to json.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question