Something more beautiful than <__main__.MyClass

2019-02-22 06:54发布

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>

标签: python class
2条回答
别忘想泡老子
2楼-- · 2019-02-22 07:15
>>> class MyClass():
...     def __init__(self, id):
...         self.id = id
...     def __repr__(self):
...         return "MyClass #%d" % self.id
... 
>>> c = MyClass(5)
>>> c
MyClass #5
查看更多
贼婆χ
3楼-- · 2019-02-22 07:18
def __repr__(self):
    return 'MyClass #%d' % (self.id,)
查看更多
登录 后发表回答