简体   繁体   中英

Python class object in array

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.

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)]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM