How to return string representation of self in a class in Python?

python

Solution

To 'pretty print' the object itself, define `__str__` like so:

class Test(object):
    def __init__(self, thing):
        self.thing = thing

    def __str__(self):
        return self.thing

 >>> a=Test('apple')
 >>> print a
 apple

If you want the representation to be custom, add `__repr__`:

class Test(object):
    def __init__(self, thing):
        self.thing = thing
    def __repr__(self):
        return self.thing 

>>> Test('pear')
pear

If you want to create a string as stated in your edit, you can do this:

class Test(object):
    def __init__(self, thing):
        self.thing = thing

    def andthis(self, other):
        return '{} and {}'.format(self.thing, other)

>>> apple=Test('apple')
>>> apple.andthis('cinnamon')
'apple and cinnamon'
>>> Test('apple').andthis('carrots')
'apple and carrots' 

Problem

Returning self in f1 gives me `<__main__.Test instance at 0x11ae48d40>`. I would like to be able to return 'apples and cinnamon' but I can't do str(self). Is there a way for me to do this? ``` class Test: def __init__(self, thing): self.thing = thing def f1(self, thing): return self + " and " + thing #<<< a = Test("apples") a.f1("cinnamon") ```

Original source