11-4. The __str__() Function

The __str__() function in a class is used to define what should be returned when the class object is converted to a string (for example, when using print()). If you don't define the __str__() function, the default string representation of the object is used, which is not very informative.

Example Without __str__()

Here’s what happens when you don’t define the __str__() function in the Car class:

Output: The default string representation, which is not very useful.

Example With __str__()

Here’s how to define the __str__() function to provide a more useful string representation for the Car class:

Custom String Representation: The __str__() function returns a formatted string that includes the yearmake, and model of the car.