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 the str()
method. Its syntax is as follows, str(object, encoding=encoding, errors=errors)
.
z = str(3.5)print(z)
repr()
: The repr()
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 x
and assigned a value of 5
to it.
Line 4: We print x
using the str()
method.
Line 5: We print x
by adding the .__str__()
method to it.
Line 7: We declare the variable y
with 7
assigned to it.
Line 8: We print the variable y
using the repr()
method.
Line 9: We print y
by 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 x
using the str()
method.
Line 6: Let's create a variable y
with a string value.
Line 7: We print y
using the repr()
method.
We observe that both functions represent a string, so let us look at them individually.
__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.
object.__str__(self)
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 receives x
and y
as arguments, and to access class-specific variables. We use the self
argument, which is a reference to the currently running instance of the class.
Line 8: we also created the __str__()
function with the self
argument, and from this, we can access the values of x
and y
. We then return the concatenation of x
and y
with a space in between.
Line 12: The class Tutorial
is instantiated, with the values "Boys" and "Scout" passed to it.
Line 13: We print the instance of the call using the str()
method.
__repr__()
methodThe 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.
object.__repr__(self)
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 the self
argument, 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 Tutorial
is 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.
__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 datetime
module.
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__()
.
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