Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 str behave in the same way:

class Bean(object):

    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2

    def __str__(self):
        return str(self.__dict__)

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

When I run:

t1 = Bean("bean 1", [Bean("bean 1.1", "same"), Bean("bean 1.2", 42)])
t2 = Bean("bean 1", [Bean("bean 1.1", "same"), Bean("bean 1.2", 42)])
t3 = Bean("bean 1", [Bean("bean 1.1", "different"), Bean("bean 1.2", 42)])

print(t1)
print(t2)
print(t3)
print(t1 == t2)
print(t1 == t3)

I get:

{'attr2': [<__main__.Bean object at 0x7fc092030f28>, <__main__.Bean object at 0x7fc092030f60>], 'attr1': 'bean 1'}
{'attr2': [<__main__.Bean object at 0x7fc091faa588>, <__main__.Bean object at 0x7fc092045128>], 'attr1': 'bean 1'}
{'attr2': [<__main__.Bean object at 0x7fc0920355c0>, <__main__.Bean object at 0x7fc092035668>], 'attr1': 'bean 1'}
True
False

since t1 and t2 contain the same values the equals return true (as expected) while since t3 contains a different value in the list the result is false (also as expected). What I would like is to have the same behavior for the to string (basically to also go in depth also for the elements in list (or set or dict ...).

For print(t1) I would like to obtain something like:

{'attr2': ["{'attr2': 'same', 'attr1': 'bean 1.1'}", "{'attr2': 42, 'attr1': 'bean 1.2'}"], 'attr1': 'bean 1'}

which is actually obtained if I do:

Bean("bean 1", [Bean("bean 1.1", "same").__str__(), Bean("bean 1.2", 42).__str__()]).__str__

Since I do not know the types of the attributes attr1, attr2 in my Bean objects (they may be lists but also sets, dictionaries etc.) is would be nice to have a simple and elegant solution that would not require type checking ...

Is this possible ?

like image 326
Valerian Avatar asked Apr 28 '17 08:04

Valerian


People also ask

How can I convert object to string?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.

Which function convert an object to a string in Python?

The answer is option D (str(x)). str(x) converts the object to a string in python.

Is object same as string Python?

Strings are objects in Python which means that there is a set of built-in functions that you can use to manipulate strings.


2 Answers

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):
    return str(self.__dict__)
like image 109
alexpeits Avatar answered Oct 20 '22 02:10

alexpeits


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

like image 44
Vinith Srinivas Avatar answered Oct 20 '22 01:10

Vinith Srinivas