python——__repr__ vs __str__的区别

176 阅读1分钟

python中将对象以友好化的方式展示有两种方式,分别是重载__repr__和重载__str__,他们有什么区别呢? 首先定义一个class

class test(object):
    def __init__(self, data):
        self.data = data

    def __repr__(self):
        return '<test> %s' % self.data

    def __str__(self):
        return '<test> value : %s' % self.data
        

声明一个test的对象:

t = test("hello")

print(t) 输出如下:

<test> value : hello

t 输出如下:

<test> hello

由此可见,print(t)调用的是__str__,面向的是用户。直接打印对象t,调用的是__repr__,面向的是程序员。

如果没有__str__,只有__repr__:

class test(object):
    def __init__(self, data):
        self.data = data

    def __repr__(self):
        return '<test> %s' % self.data

print(t)和t输出的格式都是:

<test> hello

如果只有__str__:

class test(object):
    def __init__(self, data):
        self.data = data

    def __str__(self):
        return '<test> value : %s' % self.data

则t输出

<__main__.test at 0x7fddc315f0f0>

print(t)输出

<test> value : hello

总结:print(t)优先调用__repr__,没有再调用__str__; t只调用__repr__。