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 thestr()
built-in function and by theprint()
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 therepr()
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.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.