Object To String In Python
I have some data objects on which I want to implement a to string and equals functions that go in depth. I implemented str and eq and although equality works fine I cannot make st
Solution 1:
You can use __repr__
instead of __str__
, which works recursively, although that is not a good idea most of the times (look at this answer for more details). Nevertheless, this works for me:
def__repr__(self):
returnstr(self.__dict__)
Solution 2:
You can try using repr instead of str.
I got the below output for print(t1), when using def repr(self): instead of str.
{'attr1': 'bean 1', 'attr2': [{'attr1': 'bean 1.1', 'attr2': 'same'}, {'attr1': 'bean 1.2', 'attr2': 42}]}
Let me know if this solves your problem. Attaching image for reference.
Regards, Vinith
Post a Comment for "Object To String In Python"