Why __repr__?
In Python, printing an instance object directly defaults to outputting the class from which the object was created and its address in memory (in hexadecimal)
Assuming that you want to output customized content when you use the print instance object during development and debugging, you can use the __repr__ method
Alternatively, calling an object via repr() will also return the value returned by the __repr__ method
Is it deja vu .... Yes... Same feeling as __str__ Code chestnut
class A: pass def __repr__(self): a = A() print(a) print(repr(a)) print(str(a)) # Output results <__main__.A object at 0x10e6dbcd0> <__main__.A object at 0x10e6dbcd0> <__main__.A object at 0x10e6dbcd0>
By default, __repr__() returns information about the instance object <class name object at memory address>
Override the __repr__ method
class PoloBlog: def __init__(self): = "Little Pineapple." = "/poloyy/" def __repr__(self): return "test[name=" + + ",add=" + + "]" blog = PoloBlog() print(blog) print(str(blog)) print(repr(blog)) # Output results test[name=jackfruit,add=/poloyy/] test[name=jackfruit,add=/poloyy/] test[name=jackfruit,add=/poloyy/]
Overriding only the __repr__ method will also work when using str().
class PoloBlog: def __init__(self): = "Little Pineapple." = "/poloyy/" def __str__(self): return "test[name=" + + ",add=" + + "]" blog = PoloBlog() print(blog) print(str(blog)) print(repr(blog)) # Output results test[name=jackfruit,add=/poloyy/] test[name=jackfruit,add=/poloyy/] <__main__.PoloBlog object at 0x10e2749a0>
If you only rewrite the __str__ method, repr() won't work!
The difference between str() and repr().
https:///article/
Above is Python object-oriented programming repr method example details, more information about Python object-oriented programming repr please pay attention to my other related articles!