print()函数如何工作?

时间:2017-02-18 17:38:35

标签: python pretty-print

说我有一个Element类

class Element(object):
    def __init__(self,key,val):
        self.key = key
        self.val = val

    def __str__(self):
        return '(' + str(self.key) + ',' + str(self.val) + ')'

现在,当我尝试打印包含Element类

对象的数组时
arr = [Element(10,20),Element(20,30)]
print(arr)

,输出为 -

[<maxheap.Element object at 0x01C1FCB0>, <maxheap.Element object at 0x01C270B0>]

哪个功能正在打印<maxheap.Element object at 0x01C1FCB0>?为什么在__str__(self)中调用print(Element(10,20))方法?

2 个答案:

答案 0 :(得分:0)

尝试使用索引而不是一次打印列表,如下所示:
    的     print(arr[0])
    print(arr[1])

而不是:
    的 print(arr)

修改
在这种情况下使用__repr__

答案 1 :(得分:-1)

尝试使用

def __repr__(self):

而不是

def __str__(self):