Question

I have the following python class:

class uf_node:
    def __init__(self, Vertex):
        self.vertex = Vertex
        self.rep = Vertex

    def set_rep(self, Rep):
        self.rep = Rep

Now, at the interpreter I do the following:

>>> from uf_node import *
>>> u = uf_node('a')
>>> u
<uf_node.uf_node instance at 0x7f56069ca758>

Can one get better output, perhaps creating something like a 'toString()' function that would automatically be called when you try to print the object?

Was it helpful?

Solution

The REPL invokes __repr__ function of your class. So, you can override __str__ and __repr__ functions like this

class uf_node:
    def __init__(self, Vertex):
        self.vertex = Vertex
        self.rep = Vertex

    def set_rep(self, Rep):
        self.rep = Rep

    def __str__(self):
        return "Rep: {}, Vertex: {}".format(self.rep, self.vertex)

    def __repr__(self):
        return "Rep: {}, Vertex: {}".format(self.rep, self.vertex)

With this change,

>>> u = uf_node('a')
>>> u
Rep: a, Vertex: a
>>> 

Note: You can read more about the differences between __str__ and __repr__ in this excellent answer

OTHER TIPS

You can override the str or repr class methods.

__str__ handles the conversion to a string while __repr__ is the string representation of your class you could use if your wanted to instanciate it again. __repr__ is supposed to return a valid Python expression. Both methods return a string. You usually call these methods with the string constructor str() (the str class will call the __str__ method) or the repr() function.

class uf_node(object):
    def __init__(self, Vertex):
        self.vertex = Vertex
        self.rep = Vertex

    def set_rep(self, Rep):
        self.rep = Rep

    def __str__(self):
        '''Used for string conversion'''
        return 'This node uses vertex %s' % self.vertex

    def __repr__(self):
        '''Used for string representation'''
        return 'uf_node(%s)' % repr(self.vertex)

v = uf_node('a')
print str(v) # -> 'This node used vertex a'
print repr(v) # -> "uf_node('a')

Check the doc here, it is well explained : https://docs.python.org/2/reference/datamodel.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top