Something more beautiful than <__ main __. MyClass Instance at 0x1624710>

This is my class (as far as possible):

 class MyClass(): def __init__(self, id): self.id = id def __str__(self): return "MyClass #%d" % self.id 

When I print the MyClass object, I get this beautiful line: MyClass #id . But when I just β€œshow it” in the interpreter, I still get this nasty <__main__...> . Is there any way to change this behavior?

 >>> c = MyClass(5) >>> print c MyClass #5 >>> c <__main__.MyClass instance at 0x1624710> 
+6
source share
2 answers
 def __repr__(self): return 'MyClass #%d' % (self.id,) 
+10
source
 >>> class MyClass(): ... def __init__(self, id): ... self.id = id ... def __repr__(self): ... return "MyClass #%d" % self.id ... >>> c = MyClass(5) >>> c MyClass #5 
+1
source

Source: https://habr.com/ru/post/902875/


All Articles