Python __str__ 和 __repr__ 的目的是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3691101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:16:18  来源:igfitidea点击:

What is the purpose of __str__ and __repr__?

python

提问by Daniel

I really don't understand where are __str__and __repr__used in Python. I mean, I get that __str__returns the string representation of an object. But why would I need that? In what use case scenario? Also, I read about the usage of __repr__

我真的不明白在 Python中的位置__str____repr__使用。我的意思是,我得到它__str__返回对象的字符串表示。但我为什么需要那个?在什么用例场景中?另外,我阅读了有关使用__repr__

But what I don't understand is, where would I use them?

但我不明白的是,我会在哪里使用它们?

采纳答案by miku

__repr__

__repr__

Called by the repr()built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

repr()内置函数和字符串转换(反引号)调用以计算对象的“官方”字符串表示。如果可能的话,这应该看起来像一个有效的 Python 表达式,可用于重新创建具有相同值的对象(给定适当的环境)。

__str__

__str__

Called by the str()built-in function and by the print statement to compute the "informal" string representation of an object.

str()内置函数和打印语句调用以计算对象的“非正式”字符串表示。

Use __str__if you have a class, and you'll want an informative/informal output, whenever you use this object as part of string. E.g. you can define __str__methods for Django models, which then gets rendered in the Django administration interface. Instead of something like <Model object>you'll get like first and last name of a person, the name and date of an event, etc.

使用__str__,如果你有一个类,你会希望有一个信息/非正式输出,当你使用这个对象作为字符串的一部分。例如,您可以__str__为 Django 模型定义方法,然后在 Django 管理界面中呈现这些方法。<Model object>你会得到一个人的名字和姓氏,事件的名称和日期等,而不是像这样的东西。



__repr__and __str__are similar, in fact sometimes equal (Example from BaseSetclass in sets.pyfrom the standard library):

__repr__并且__str__相似,实际上有时相等(来自标准库中的BaseSet类的示例sets.py):

def __repr__(self):
    """Return string representation of a set.

    This looks like 'Set([<list of elements>])'.
    """
    return self._repr()

# __str__ is the same as __repr__
__str__ = __repr__

回答by Peter Rowell

Grasshopper, when in doubt go to the mountainand read the Ancient Texts. In them you will find that __repr__() should:

蝈蝈,在怀疑的时候去山上阅读古代典籍。在其中你会发现 __repr__() 应该:

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value.

如果可能的话,这应该看起来像一个有效的 Python 表达式,可用于重新创建具有相同值的对象。

回答by Scott Griffiths

The one place where you use them both a lot is in an interactive session. If you print an object then its __str__method will get called, whereas if you just use an object by itself then its __repr__is shown:

您经常使用它们的一个地方是在交互式会话中。如果你打印一个对象,那么它的__str__方法将被调用,而如果你只使用一个对象本身,那么它__repr__会显示:

>>> from decimal import Decimal
>>> a = Decimal(1.25)
>>> print(a)
1.25                  <---- this is from __str__
>>> a
Decimal('1.25')       <---- this is from __repr__

The __str__is intended to be as human-readable as possible, whereas the __repr__should aim to be something that could be used to recreate the object, although it often won't be exactly how it was created, as in this case.

The__str__旨在尽可能让人类可读,而__repr__should 旨在成为可用于重新创建对象的东西,尽管它通常不会完全是它的创建方式,就像在这种情况下一样。

It's also not unusual for both __str__and __repr__to return the same value (certainly for built-in types).

这也是不寻常的都__str____repr__返回相同的值(当然,对于内置类型)。

回答by user1767754

Building up and on the previous answers and showing some more examples. If used properly, the difference between strand repris clear. In short reprshould return a string that can be copy-pasted to rebuilt the exact state of the object, whereas stris useful for loggingand observingdebugging results. Here are some examples to see the different outputs for some known libraries.

在之前的答案的基础上建立并展示更多示例。如果使用得当,之间的区别strrepr明确。总之repr应返回的字符串,可以是复制粘贴到重建对象的确切状态,而str为有用loggingobserving调试的结果。以下是一些示例,用于查看某些已知库的不同输出。

Datetime

约会时间

print repr(datetime.now())    #datetime.datetime(2017, 12, 12, 18, 49, 27, 134411)
print str(datetime.now())     #2017-12-12 18:49:27.134452

The stris good to print into a log file, where as reprcan be re-purposed if you want to run it directly or dump it as commands into a file.

str是好事,打印到日志文件中,那里的repr,如果你想直接运行或转储它作为命令到一个文件可以重新旨意。

x = datetime.datetime(2017, 12, 12, 18, 49, 27, 134411)

Numpy

麻木

print repr(np.array([1,2,3,4,5])) #array([1, 2, 3, 4, 5])
print str(np.array([1,2,3,4,5]))  #[1 2 3 4 5]

in Numpy the repris again directly consumable.

在 Numpy 中,它又repr是直接消耗品。

Custom Vector3 example

自定义 Vector3 示例

class Vector3(object):
    def __init__(self, args):
        self.x = args[0]
        self.y = args[1]
        self.z = args[2]

    def __str__(self):
        return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z)

    def __repr__(self):
        return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z)

In this example, reprreturns again a string that can be directly consumed/executed, whereas stris more useful as a debug output.

在这个例子中,repr再次返回一个可以直接使用/执行的字符串,而str作为调试输出更有用。

v = Vector3([1,2,3])
print str(v)     #x: 1, y: 2, z: 3
print repr(v)    #Vector3([1,2,3])

One thing to keep in mind, if strisn't defined but repr, strwill automatically call repr. So, it's always good to at least define repr

要记住的一件事,如果str没有定义但是reprstr将自动调用repr. 所以,至少定义一下总是好的repr

回答by Vishvajit Pathak

strwill be informal and readable format whereas reprwill give official object representation.

str将是非正式和可读的格式,而repr将提供正式的对象表示。

class Complex:
    # Constructor
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag

    # "official" string representation of an object
    def __repr__(self):
        return 'Rational(%s, %s)' % (self.real, self.imag)

    # "informal" string representation of an object (readable)
    def __str__(self):
        return '%s + i%s' % (self.real, self.imag)

    t = Complex(10, 20)

    print (t)     # this is usual way we print the object
    print (str(t))  # this is str representation of object 
    print (repr(t))  # this is repr representation of object   

Answers : 

Rational(10, 20) # usual representation
10 + i20      # str representation
Rational(10, 20)  # repr representation

回答by Zorana

Lets have a class without __str__function.

让我们有一个没有__str__功能的类。

class Employee:

    def __init__(self, first, last, pay):
        self.first = first 
        self.last = last
        self.pay = pay

emp1 = Employee('Ivan', 'Smith', 90000)

print(emp1)

When we print this instance of the class, emp1, this is what we get:

当我们打印这个类的实例时,emp1我们得到:

<__main__.Employee object at 0x7ff6fc0a0e48>

This is not very helpful, and certainly this is not what we want printed if we are using it to display (like in html)

这不是很有帮助,当然,如果我们使用它来显示(如在 html 中),这肯定不是我们想要打印的

So now, the same class, but with __str__function:

所以现在,同一个类,但具有__str__功能:

class Employee:

    def __init__(self, first, last, pay):
        self.first = first 
        self.last = last
        self.pay = pay

    def __str__(self):
        return(f"The employee {self.first} {self.last} earns {self.pay}.")
        # you can edit this and use any attributes of the class

emp2 = Employee('John', 'Williams', 90000)

print(emp2)

Now instead of printing that there is an object, we get what we specified with return of __str__function:

现在不是打印有一个对象,我们得到了我们指定的__str__函数返回值:

The employee John Williams earns 90000

The employee John Williams earns 90000