What are the similarities and differences between __str__ and __repr__ in Python?

WBOY
Release: 2023-04-29 19:58:05
forward
1566 people have browsed it

What are the similarities and differences between __str__ and __repr__?

Representation of string

We all know that Python’s built-in function repr() can convert objects Express it in the form of a string to facilitate our identification. This is the "string representation". repr() uses the special method __repr__ to get the string representation of an object. 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()))>>> print(repr(Example()))>>> 
>>> str(Example)
""
>>> repr(Example())
''
Copy after login

**__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 "informal" or well-formed characters of an object String representation. The return value must be a string object.

  • __repr__: is called by the repr() built-in function 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 continue 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
Copy after login

When x=4, when x is an integer type, the return results of calling str() and repr() It's 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)'
>>>
Copy after login

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))
Copy after login

Output result:

Name:Alice
Name:Alice
姓名:Alice
Copy after login

The above is the detailed content of What are the similarities and differences between __str__ and __repr__ in Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template