Q6: What is the purpose of the __str__ and __repr__ methods in Python classes, and how do they differ in their use cases?
A6:
__str__Method:- The
__str__method is responsible for returning a human-readable string representation of an object. - It is invoked when the
str()function is used on an object or when theprint()function is called with the object as an argument. - This method is typically used for displaying information to end-users in a readable format.
pythonclass MyClass: def __str__(self): return "This is an instance of MyClass." obj = MyClass() print(str(obj)) # Output: This is an instance of MyClass.- The
__repr__Method:- The
__repr__method is responsible for returning an unambiguous string representation of an object, primarily for debugging purposes. - It is invoked when the
repr()function is used on an object or when the backtick notation (``) is used in Python 2 (Note: backticks are not used for repr in Python 3). - This method is used by developers to obtain detailed information about an object.
pythonclass MyClass: def __repr__(self): return "MyClass()" obj = MyClass() print(repr(obj)) # Output: MyClass()- The
In summary, __str__ is for creating a readable representation of an object for end-users, while __repr__ is intended for developers to obtain an unambiguous and detailed representation of an object for debugging and development purposes.