2

I'm trying to make an array of class objects. When I create the object, it works great:

class Complex(object):

    def __init__(self, realpart, imagpart):
        #creates complex number
        self.r = realpart
        self.i = imagpart

    def __str__(self):
        '''Returns complex number as a string'''
        return '(%s + %s j)' % (self.r, self.i) 

a = Complex(1,0)
print a

(1 + 0 j)

But when I try to put a in an array, I get an error:

arr1 = [a]

[<__ main __.Complex object at 0x5afab0>]

Why could this be happening? Thanks in advance.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497

2 Answers2

3

Because __repr__ was used instead of __str__. Override __repr__ as Ashwini Chaudhary commented.

>>> class Complex(object):
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...     def __str__(self):
...         '''Returns complex number as a string'''
...         return '(%s + %s j)' % (self.r, self.i)
...     __repr__ = __str__ # <-----
...
>>> a = Complex(1,0)
>>> [a]
[(1 + 0 j)]
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    Note that it may be better to provide a less ambiguous `repr` representation, such as `Complex(1, 0)`. With this implementation, it's difficult to tell exactly what kind of object you're dealing with. It looks like the built-in type, but slightly mangled. – user2357112 Jan 22 '14 at 08:10
1

As per the docs, print normally calls __str__, so when you printed the object, __str__ is invoked. But when you print the builtin collections, the __str__ method of them invoke __iter__ of the individual elements in it. So, your must implement __iter__ on your own, or let the default __repr__ as it is.

If you decide to implement __repr__ yourself, the docs say,

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object.

So, if you are implementing it yourself, give as much information as possible, so that the __repr__ output is unambiguous and useful for debugging.

def __str__(self):
    '''Returns complex number as a string'''
    return '< Complex({} + {}j) >'.format(self.r, self.i) 

You can read more about this, in this answer.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497