0%

python__str__与__repr__

__str__

__str__会在print(实例)的时候打印,代替默认的内存地址信息。

1
2
3
4
5
6
7
8
9
10
class Human():
def __init__(self, name):
self.name = name

def __str__(self):
return "Human name\'s " + self.name


fred = Human('fred')
print(fred)

结果:

1
Human name's fred

我们用python解释器再来一遍:

1
2
3
4
5
6
7
8
9
10
>>> class Human():
... def __init__(self, name):
... self.name = name
... def __str__(self):
... return "Human name\'s " + self.name
...
>>> fred = Human('fred')
>>> fred
<__main__.Human object at 0x0000015DE4A7D9B0>
>>>

__repr__

__repr__也会在print(实例)的时候打印,并且会在python解释器中显示。
python解释器中:

1
2
3
4
5
6
7
8
9
10
>>> class Human():
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return "Human name\'s " + self.name
...
>>> fred = Human('fred')
>>> fred
Human name's fred
>>>

str()repr()

对比str()repr()str方便程序员理解,repr方便interpreter(解释器)理解。

1
2
3
name = 'fred'
print(str(name))
print(repr(name))

结果:

1
2
fred
'fred'

end