Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Something more beautiful than <__main__.MyClass instance at 0x1624710>

Tags:

python

class

This is my class (as simple as it can be):

class MyClass():
    def __init__(self, id):
        self.id = id

    def __str__(self):
        return "MyClass #%d" % self.id

When I print an object of MyClass, I get this beautiful string: MyClass #id. But when I just "show it" in the interpreter, I still get this nasty <__main__...>. Is there a way to change this behaviour?

>>> c = MyClass(5)
>>> print c
MyClass #5
>>> c
<__main__.MyClass instance at 0x1624710>
like image 351
juliomalegria Avatar asked Dec 01 '11 22:12

juliomalegria


2 Answers

def __repr__(self):
    return 'MyClass #%d' % (self.id,)
like image 169
rob mayoff Avatar answered Oct 13 '22 00:10

rob mayoff


>>> class MyClass():
...     def __init__(self, id):
...         self.id = id
...     def __repr__(self):
...         return "MyClass #%d" % self.id
... 
>>> c = MyClass(5)
>>> c
MyClass #5
like image 26
unbeli Avatar answered Oct 13 '22 01:10

unbeli