What is the __repr__() method used for in Python classes?
a) To provide a formal string representation of the object for debugging
b) To compare two objects
c) To initialize an object’s attributes
d) To create a copy of an object
Answer:
a) To provide a formal string representation of the object for debugging
Explanation:
The __repr__()
method in Python is used to provide a formal string representation of the object. This method is primarily used for debugging and development purposes. The output of __repr__()
should be unambiguous and, if possible, match the way the object can be recreated using Python code.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def __repr__(self):
return f"Car(make='{self.make}', model='{self.model}')"
# Creating an object of Car class
my_car = Car("Toyota", "Corolla")
print(repr(my_car)) # Output: Car(make='Toyota', model='Corolla')
In this example, the __repr__()
method provides a string that shows the Car
object in a way that is useful for debugging. The string includes the class name and the values of the object’s attributes, making it clear what the object represents.
Having a well-defined __repr__()
method in your classes is important for debugging and logging, as it helps developers quickly understand the state of an object.