使用自定义类打印字典作为值不会调用其字符串方法?

时间:2016-02-17 14:29:33

标签: python dictionary tostring

我正在使用python中的类进行操作,并编写了2个小类:

class ClaElement:

    start = None
    end = None
    basesLeft = None
    orientation = None
    contig = None
    size = None

    def __init__(self, contig, start, end, orientation, basesLeft=None):

        self.contig = contig
        self.start = start
        self.end = end
        self.orientation = orientation
        self.basesLeft = basesLeft

        self.size = self.end - self.start

    def __str__(self):
        return "{ClaElement: "+str(self.contig)+"_"+str(self.start)+"_"+str(self.end)+"_"+str(self.orientation)+"}"

    def getSize(self):
        return self.size

class ClaCluster:

    contig = None
    clusterElements = []

    def __init__(self, contig, firstElement):
        self.contig = contig
        self.addElement(firstElement)

    def addElement(self, claElement):
        self.clusterElements.append(claElement)

    def getFirst(self):
        return self.clusterElements[0]

    def getLast(self):
        return self.clusterElements[-1]

    def getElements(self):
        return self.clusterElements

    def getContig(self):
        return self.contig

    def __str__(self):
        return "{ClaCluster: "+str(self.contig)+" "+str(len(self.clusterElements))+" elements}"

我的测试主:

from ClaElement import ClaElement
from ClaCluster import ClaCluster

if __name__ == '__main__':

    ele = ClaElement("x",1,2,"left")

    claDict = dict()

    cluster = ClaCluster("x", ele)

    claDict["hello"] = cluster

    print(claDict)
    print(claDict["hello"])
    print(ele)

这导致以下输出:

{'hello': <ClaCluster.ClaCluster object at 0x7fe8ee04c5f8>}
{ClaCluster: x 1 elements}
{ClaElement: x_1_2_left}

现在我的问题是为什么我的第一个输出打印内存地址,即使我为我的类ClaCluster提供了一个功能正常的字符串方法?有没有办法在我打印字典时调用该方法,或者我必须手动迭代?

1 个答案:

答案 0 :(得分:4)

内置__str__()类型的dict方法使用您班级的__repr__()方法,而非__str__()。只需重命名您的方法,一切都应该正常工作。