How to Customize the String Representation of Class Instances with print()
When printing instances of a class, the default behavior often displays the memory location of the object. To customize the string representation and control what is shown when printing, you can implement two special methods: str and __repr__.
__str__: Defining the Human-Readable String Representation
The str method defines the string representation of an object for general use. It is invoked when you call print() or str() on the object. By overriding __str__, you can define the custom output that is displayed when printing.
__repr__: Defining the String Representation for Debugging
The repr method defines the string representation intended for debugging purposes. It is invoked when you call repr() on the object or if you do not define str__. The __repr representation should be a valid Python expression that evaluates to the object.
Example
To customize the string representation of your class instances:
class Test: def __init__(self): self.a = 'foo' def __str__(self): return "member of Test" def __repr__(self): return "Test()"
In the example above:
When you print an instance of this class:
t = Test() print(t)
It will display "member of Test" on the console, providing a custom and meaningful representation.
The above is the detailed content of How to Override `__str__` and `__repr__` for Customized Print Output of Class Instances?. For more information, please follow other related articles on the PHP Chinese website!