数组中的 Python 类对象

标签 python list

我正在尝试创建一个类对象数组。当我创建对象时,它工作得很好:

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)

但是当我尝试将 a 放入数组时,出现错误:

arr1 = [a]

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

为什么会发生这种情况?提前致谢。

最佳答案

因为使用了__repr__而不是__str__。覆盖 Ashwini Chaudhary 评论的 __repr__

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

关于数组中的 Python 类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21276998/

相关文章:

java - 一个 ListView 中的多个列表

python - 并行运行 for 循环中的所有迭代

python - 这个字符串操作在Python中是如何工作的?

python - 使用 matplotlib 显示稀疏箭袋箭头

python - Tensorflow,如何访问 RNN 的所有中间状态,而不仅仅是最后一个状态

python - 如何从 BeautifulSoup4 的 html 标签中找到特定的数据属性?

list - 使可扩展列表的背景透明似乎是不可能的。在 StackOverflow 上测试了所有解决方案

python - 为什么 .join() 是字符串的属性而不是列表?

python 列表创建,包括生成器和非生成器

python - 如何在python中存储绝对路径并将其显示为目录结构?