What is the difference between __str__ and __repr__?
The object class in Python offers a variety of magic methods. Magic methods start and end with double underscores—we never explicitly invoke these methods. The appropriate built-in function makes an internal call to one of these magic methods.
In this Answer, we will only discuss str() and repr() functions which both call the magic methods __str__() and __repr__() respectively.
str(): The object's string representation is returned by thestr()method. Its syntax is as follows,str(object, encoding=encoding, errors=errors).
z = str(3.5)print(z)
repr(): Therepr()function returns a printed representation of an object. Its syntax is as follows,repr(object).
print(repr(['x', 'y', 'z']))
Let's see how the two functions are related. We'll check it out using integers and strings.
#we will create two variables and assign a variable to them#we will print them out using the __str__() and __repr__() respectivelyx = 5print(str(x))print(x.__str__())y = 7print(repr(y))print(y.__repr__())
Line 3: We declare a variable
xand assigned a value of5to it.Line 4: We print
xusing thestr()method.Line 5: We print
xby adding the.__str__()method to it.Line 7: We declare the variable
ywith7assigned to it.Line 8: We print the variable
yusing therepr()method.Line 9: We print
yby assing the.__repr__()method to it.
#lets create a variable x with a string value and print using the str() funtionx = 'Programming is fun!'print (str(x))#lets create a variable y with a string value and print using the repr() funtiony = 'Learn how to code on Educative'print (repr(y))
Line 2: We assign a string value to
x.Line 3: We print
xusing thestr()method.Line 6: Let's create a variable
ywith a string value.Line 7: We print
yusing therepr()method.
We observe that both functions represent a string, so let us look at them individually.
The __str__() method
Classes can utilize the __str__() method to express class objects as strings. The __str__() method definition ought to be written so that it outputs all of the class members and is simple to understand. When inspecting the members of a class, this technique is also employed as a debugging tool.
When the print() or str() functions are used on an object and return a string, the __str__() method is triggered.
Syntax
object.__str__(self)
Example
Let's create a class, Tutorial, and define the __str__() method. We'll then call this method using the built-in Python function, str().
#create class Tutorialclass Tutorial:#lets pass two arguments into the __init__ functiondef __init__(self, x, y):self.x = xself.y = y#using the __str__() method we return the values passed into the x and y arguments.def __str__(self):result = self.x + ' ' + str(self.y)return resulttuts = Tutorial("Boys", "Scout")print(str(tuts))
Line 2: We create a class called
Tutorial.Line 4: The
__init__()function in the class receivesxandyas arguments, and to access class-specific variables. We use theselfargument, which is a reference to the currently running instance of the class.Line 8: we also created the
__str__()function with theselfargument, and from this, we can access the values ofxandy. We then return the concatenation ofxandywith a space in between.Line 12: The class
Tutorialis instantiated, with the values "Boys" and "Scout" passed to it.Line 13: We print the instance of the call using the
str()method.
The __repr__() method
The object representation is returned as a string by the Python method, __repr__(). This method is called when the object's repr() method is used. If feasible, the text returned should be a legitimate Python expression that may be used to recreate the object.
Using the __repr__() method, we can create a custom string representation of our class objects.
Syntax
object.__repr__(self)
Example
We will create a class, Tutorial, and define the __repr__() method. We can then call this method using the built-in Python function, repr().
#We will create the class Tutorialclass Tutorial:#the init function will receive two argument - name and sex.def __init__(self, name, sex):self.name = nameself.sex = sexdef __repr__(self):result = self.name + ' is a ' + str(self.sex)return result# Let's make a Person object and print the results of repr()tuts = Tutorial("Michael Jackson", "Male")print(repr(tuts))
Line 2: We create a class,
Tutorial.Line 4: The
__init__()function in the class receives "name" and "sex" as arguments.Line 8: We create the
__repr__()function with theselfargument, and from this, we can access the values of "name" and "sex". We then return the concatenation of both arguments with a space in between.Line 15: The class
Tutorialis instantiated, and the values "Michael Jackson" and "Male" are passed to it.Line 16: We print the instance of the call using the
repr()method.
Difference between __str__() and __repr__()
The
__str__()method is intended to return information in a readable format for humans to easily understand it. It is perfect for logging or displaying object information. While the__repr__()method's goal is to deliver a string representation of the object that may be used to replicate it, it is also designed to do the opposite.A unique string representation of our class objects may be made using the
__repr__()method.The goal of
__repr__()is to be unambiguous, while the goal of__str__()is to be readable.__str__()of a container utilizes the__repr__()of contained objects.
Let's look at a common class where the __str__() and __repr__ () methods are defined.
#lets import the datetime moduleimport datetime#lets get the current date and timenow = datetime.datetime.now()print('Using str: ' + now.__str__())print('Using repr: ' + now.__repr__())
Line 2: We import the
datetimemodule.Line 5: Using the
datetime.datetime.now(), we get the current date and time. Note that it is the current date and time on our local computer.Line 6: We print the date using the
__str__()method.Line 7: We print the date using the
__repr__()method. There is a difference in the output.
We'll utilize __repr__() to implement whatever class we choose. It should come naturally to do this. We implement __str__() if it would be advantageous to have a string version that errs on the side of readability. Backup behavior is supplied by __repr__() in the absence of __str__().
Conclusion
The __str__() and __repr__() methods return the object's string representation. The __repr__() representation is intended to hold information about the object so that it may be created again. In contrast, the __str__() string representation is human-friendly and mainly used for logging reasons. Always utilize the str() and repr() functions instead of using these methods directly.
Free Resources