python中 str 和 repr_python中__str__与__repr__的区别

str__和__repr

__str__和__repr__都是python的内置方法,都用与将对象的属性转化成人类容易识别的信息,他们有什么区别呢

来看一段代码

from math import hypot

class Vector:

def __init__(self, x, y):

self.x = x

self.y = y

def __str__(self):

return 'Vector(%r,%r)' % (self.x, self.y)

def __abs__(self):

return hypot(self.x, self.y)

def __bool__(self):

return bool(abs(self))

def __add__(self, other):

x = self.x + other.x

y = self.y + other.y

return Vector(x,y)

def __mul__(self, scalar):

"""相乘时调用__mul__方法"""

return Vector(self.x * scalar, self.y * scalar)

在控制台进行如下输入

```python

from cheapter_1.vector import Vector

v1=Vector(3,4)

v1

print(v1)

Vector(3,4)

把__str__换成__repr__

```python

def __repr__(self):

return 'Vector(%r,%r)' % (self.x, self.y)

在控制台重复上述操作

```python

from cheapter_1.vector import Vector

v1 = Vector(3,4)

v1

Vector(3,4)

print(v1)

Vector(3,4)

```

同时定义__str__和__repr__

def __str__(self):

return "in __str__"

def __repr__(self):

return 'Vector(%r,%r)' % (self.x, self.y)

在控制台进行以下操作

```python

from cheapter_1.vector import Vector

v1=Vector(3,4)

v1

Vector(3,4)

print(v1)

in __str__

## 小结

__str__和__repr__的区别主要有以下几点

- __str__是面向用户的,而__repr__面向程序员去找

- 打印操作会首先尝试__str__和str内置函数(print运行的内部等价形式),如果没有就尝试__repr__,都没有会输出原始对象形式

- 交互环境输出对象时会调用__repr__

更多关于__str__与__repr__的区别:Difference between __str__ and __repr__?

本文部分代码来源:fluent python by Luciano Ramalho(O'Reilly).Copyright 2015 Luciano Ramalho,978-1-491-94600-8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值