Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print dict with custom class as values wont call their string method?

I was messing around with classes in python and wrote 2 little ones:

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}"

And my test-main:

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)

This leads to the following output:

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

Now my question is why is the output of my first print the memory address even though I provided a functioning string-method for my class ClaCluster? Is there a way to get the method invoked when I am printing the dictionary or do I have to iterate by hand?

like image 838
voiDnyx Avatar asked Feb 17 '16 14:02

voiDnyx


People also ask

Should I use dict () or {}?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

How do you print a class str in Python?

Python __str__() This method is called when print() or str() function is invoked on an object. This method must return the String object. If we don't implement __str__() function for a class, then built-in object implementation is used that actually calls __repr__() function.

Can a dictionary value be a string?

Dictionary values can be just about anything (int, lists, functions, strings, etc).

How do I turn a class into a dictionary in Python?

By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.


1 Answers

The __str__() method of the built-in dict type uses the __repr__() method of your class, not __str__(). Simply rename your method, and all should work fine.

like image 119
Sven Marnach Avatar answered Oct 06 '22 00:10

Sven Marnach