What does the __str__() method do in a Python class?
a) Returns a string representation of the object
b) Compares two objects
c) Initializes an object
d) Destroys an object
Answer:
a) Returns a string representation of the object
Explanation:
The __str__()
method in a Python class returns a string representation of the object. This method is called when you print an object or convert it to a string using str()
. It is intended to provide a readable and informative representation of the object, suitable for end-users.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def __str__(self):
return f"{self.make} {self.model}"
# Creating an object of Car class
my_car = Car("Toyota", "Corolla")
print(my_car) # Output: Toyota Corolla
In this example, the __str__()
method is used to return a string that represents the Car
object in a readable format. When you print the object, the output is the string returned by __str__()
.
Defining the __str__()
method in your classes is important for making your objects more user-friendly and easier to understand when displayed or logged.