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)



在控制台进行如下输入

from cheapter_1.vector import Vector
v1=Vector(3,4)
v1
<cheapter_1.vector.Vector object at 0x000001D7B67BDA90>
print(v1)
Vector(3,4)



把__str__换成__repr__

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



在控制台重复上述操作

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)



在控制台进行以下操作

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

猜你喜欢

转载自www.cnblogs.com/zzliu/p/10787606.html