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:
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year my_car = Car("Toyota", "Corolla", 2020) print(my_car) # Output: <__main__.Car object at 0x7f8e3c29f700> |
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:
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def __str__(self): return f"{self.year} {self.make} {self.model}" # Creating an object of the Car class my_car = Car("Toyota", "Corolla", 2020) # Printing the object print(my_car) # Output: 2020 Toyota Corolla |
Custom String Representation: The __str__() function returns a formatted string that includes the year, make, and model of the car.