Home  >  Article  >  Backend Development  >  A thorough understanding of __str__ and __repr__ in Python in one article

A thorough understanding of __str__ and __repr__ in Python in one article

PHPz
PHPzforward
2023-04-10 14:51:102111browse

__str__ and __repr__What are the similarities and differences?

String representation

We all know that Python’s built-in function repr()​ can convert objects in the form of strings Express it so that we can identify it easily. This is the "string representation". repr()​ obtains the string representation of an object through the special method __repr__​. If __repr__ is not implemented, when we print a vector instance to the console, the resulting string may be .

>>> class Example: pass

>>> print(str(Example()))
<__main__.Example object at 0x10a514f98>
>>> print(repr(Example()))
<__main__.Example object at 0x1088eb438>
>>> 
>>> str(Example)
"<class '__main__.Example'>"
>>> repr(Example())
'<__main__.Example object at 0x1088eb438>'

**__str__**​vs.**__repr__**

Next let’s take a look at the similarities and differences between **__str__** and **__repr__**​. According to the official Python documentation:

  • __str__​: Called by str(object) and the built-in functions format() and print() to generate an "informal" or well-formatted string representation of an object . The return value must be a string object.
  • __repr__​: It is called by the repr() built-in function and is used to output the "official" string representation of an object. The return value must be a string object. This method is usually used for debugging. The default implementation defined for the built-in type object calls object.__repr__().

You are confused about formal and informal formats, right? It’s okay, let’s go on to see:

1. Both can output objects

>>> x = 4
>>> repr(x)
'4'
>>> str(x)
'4'
>>> y = 'pythonic'
>>> repr(y)
"'pythonic'"
>>> str(y)
'pythonic'

>>> z = '4'
>>> repr(z)
"'4'"
>>> str(z)# 注意,此处的输出结果形式跟str(x)一样,但x和z的类型并不一样
'4'
>>> str(x) == str(z)
True
>>> repr(x) == repr(z)
False
>>> str(4) == str("4")
True
>>> repr(4) == repr("4")
False

When x=4, when x is an integer type, the return of calling str()​ and repr() The result is the same,

And when y is a string type, the result of repr(y)​ is a "formal" string representation, while the result of str(y)​ is "informal" . str() allows us to understand the content of the object most quickly and is more readable.

2 .__str__​ is readable, and the goal of __repr__ is clear

>>> import datetime
>>> d = datetime.datetime.now()
>>> str(d)
'2020-04-04 20:47:46.525245'
>>> repr(d)
'datetime.datetime(2020, 4, 4, 20, 47, 46, 525245)'
>>>

It can be seen that repr() can better display the type, value and other information of the object, and the object description is clear of.

It is called when the str()​ function is used, or when an object is printed using the print function, and the string it returns is more friendly to end users.

3. Rewrite __repr__​, which will also use __str_

class Student():

def __init__(self, name):
self.name = name

def __str__(self):
return "Name:" + self.name

def __repr__(self):
return "姓名:" + self.name


class_one = Student("Alice")
print(class_one)
print(str(class_one))
print(repr(class_one))

Output results:

Name:Alice
Name:Alice
姓名:Alice

Summary

Common points: They are all used To output an object

Difference:

  1. __str__​ The target is readable, __str__() is not expected to return a valid Python expression, but can be used more conveniently or More accurate descriptive information. The goal of
  2. __repr__ is clear. The returned string should be accurate, unambiguous, and express as much as possible how to create the printed object using code.
  3. The use of the container’s __str__​ method contains the object’s __repr__​

The above is the detailed content of A thorough understanding of __str__ and __repr__ in Python in one article. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete