我真的不明白的地方都__str__
和__repr__
Python中使用.我的意思是,我得到它__str__
返回一个对象的字符串表示.但为什么我需要呢?在什么用例场景?另外,我读到了有关的用法__repr__
但我不明白的是,我会在哪里使用它们?
mik*_*iku 78
由
repr()
内置函数和字符串转换(反向引号)调用,以计算对象的"官方"字符串表示形式.如果可能的话,这应该看起来像一个有效的Python表达式,可用于重新创建具有相同值的对象(给定适当的环境).
由
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表达式,可用于重新创建具有相同值的对象.
use*_*754 11
建立以前的答案,并展示更多的例子.如果使用得当,之间的区别str
和repr
明确.总之repr
应当返回一个可复制粘贴到重建对象的确切状态的字符串,而str
为有用logging
和observing
调试结果.以下是一些示例,可以查看某些已知库的不同输出.
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)
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
再次直接消耗品.
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
归档时间: |
|
查看次数: |
75741 次 |
最近记录: |