What is the difference between __str__ and __repr__ IN PYTHON?

0
0

In Python, both __str__ and __repr__ are special methods that can be defined in a class to control how instances of that class are represented as strings. However, they are intended for different purposes and have different default behaviors:

  • __str__(self) is used to return a human-readable string representation of an object. This method is called by the str() built-in function and by the print() function. The default implementation returns the result of the __repr__() method, but you can override it to provide a more meaningful string representation. This method should be used for display purposes.
  • __repr__(self) is used to return an unambiguous string representation of an object that can be used to recreate that object. This method is called by the repr() built-in function and by the interactive interpreter when evaluating expressions that contain objects. The default implementation returns a string that looks like a constructor call that could be used to recreate the object. This method should be used for debugging and development purposes.

Here’s an example that illustrates the difference:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f”{self.name}, {self.age} years old”

def __repr__(self):
return f”Person(‘{self.name}’, {self.age})”

person = Person(“Alice”, 30)
print(person) # Output: Alice, 30 years old
print(repr(person)) # Output: Person(‘Alice’, 30)

 

In this example, the __str__ method returns a human-readable string representation of the Person object, while the __repr__ method returns a string that looks like a constructor call that can be used to recreate the Person object. Note that repr(person) returns a string that includes single quotes around the name, while print(person) does not. This is because repr() includes quotes to indicate that the name is a string, while print() does not need to include them because it is clear that name is a string.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.