__str__和__repr__的目的是什么?

Dan*_*iel 74 python

我真的不明白的地方都__str____repr__Python中使用.我的意思是,我得到它__str__返回一个对象的字符串表示.但为什么我需要呢?在什么用例场景?另外,我读到了有关的用法__repr__

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

mik*_*iku 78

__repr__

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

__str__

str()内置函数和print语句调用,以计算对象的"非正式"字符串表示形式.

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


__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__
Run Code Online (Sandbox Code Playgroud)


Sco*_*ths 53

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:

>>> from decimal import Decimal
>>> a = Decimal(1.25)
>>> print(a)
1.25                  <---- this is from __str__
>>> a
Decimal('1.25')       <---- this is from __repr__
Run Code Online (Sandbox Code Playgroud)

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.

It's also not unusual for both __str__ and __repr__ to return the same value (certainly for built-in types).


Pet*_*ell 14

蝈蝈,有疑问时去山上阅读古代典籍.在其中你会发现__repr __()应该:

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

  • -1因为这甚至没有尝试回答实际问题,这就是用例. (6认同)
  • 那么文档仍然没有说*如何使用它进行调试,但我真的不打算对此进行论证.我们至少同意你的答案没有解决这个问题,所以我的-1对我来说仍然是合理的.如果问题写得不好/重复/无关紧要,那么您可以帮助改进问题,链接到重复项,或者简单地向下投票.我认为我的主要反对意见是答案应该试着回答这个问题 - 还有其他批评这个问题的机制.我现在闭嘴了,因为我觉得我们这里有更好的事情要做. (5认同)
  • @Scott:你是对的.但是,*实际问题*首先表明绝对没有尝试过主要文档.提出一个问题表明你已经试图自己回答这个问题,但仍然对它的某些方面感到有些困惑,并且发布这样的问题完全是另一回事.只是输入他的主题作为一个新问题,显示前六名中的5个建议SO线程会回答他的问题,但他不能被打扰.我没有给他一个轻松的答案,但我受到了极大的诱惑. (3认同)

use*_*754 11

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

约会时间

print repr(datetime.now())    #datetime.datetime(2017, 12, 12, 18, 49, 27, 134411)
print str(datetime.now())     #2017-12-12 18:49:27.134452
Run Code Online (Sandbox Code Playgroud)

str是好事,打印成一个日志文件,其中如repr可以,如果你想直接运行或转储它作为命令到一个文件中重新利用.

x = datetime.datetime(2017, 12, 12, 18, 49, 27, 134411)
Run Code Online (Sandbox Code Playgroud)

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]
Run Code Online (Sandbox Code Playgroud)

在Numpy,repr再次直接消耗品.

自定义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)
Run Code Online (Sandbox Code Playgroud)

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

v = Vector3([1,2,3])
print str(v)     #x: 1, y: 2, z: 3
print repr(v)    #Vector3([1,2,3])
Run Code Online (Sandbox Code Playgroud)

有一点要记住,如果str没有定义,但是repr,str会自动调用repr.所以,至少定义总是好的repr


小智 6

让我们有一个没有__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)
Run Code Online (Sandbox Code Playgroud)

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

<__main__.Employee object at 0x7ff6fc0a0e48>
Run Code Online (Sandbox Code Playgroud)

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

所以现在,同一个类,但具有__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)
Run Code Online (Sandbox Code Playgroud)

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

The employee John Williams earns 90000