美文网首页
python里面的str和repr

python里面的str和repr

作者: 思而忧 | 来源:发表于2017-08-21 18:44 被阅读0次

python 对象属性中的__repr__ & __str__

例子

class test_object(object):
    pass

print str(test_object())
<__main__.test_object object at 0x037C9F90>
print repr(rest_object())
<__main__.test_object object at 0x037C9F90>

class test_object(object):
    def __repr__(self):
        return 'foo'
print str(test_object())
foo
print repr(test_object())
foo

class test_object(object):
    def __str__(self):
        return 'foo'
print str(test_object())
foo
print repr(test_object())
<__main__.test_object object at 0x037C9F90>
class test_object(object):
    def __str__(self):
        return 'foo'
    def __repr__(self):
        return 'foo2'

print str(test_object())
foo
print repr(test_object())
foo2

 

从上面可以看出如果程序修改了__repr____str__会自动被重载,而__str__重写后不会被__repr__

__str__ 是保证对象的可读性,方便用户查看信息。

__repr__是保证对象的准确性,让程序员处理对象的时候更加精确。

相关文章

  • python里面的str和repr

    python 对象属性中的__repr__ & __str__ 例子 从上面可以看出如果程序修改了__repr__...

  • Python中__repr__和__str__区别

    Python中repr和str区别 原创 2016年12月14日 23:21:25 标签: python 看下面的...

  • Python 输入输出

    str和repr内置函数 在介绍Python的输入输出之前,我们先来介绍两个内置函数,str()和repr(),它...

  • python中str和repr有什么区别?

    python中str和repr有什么区别?下面给大家详细介绍: 1、内建函数str()和repr() 或反引号操作...

  • 特殊函数

    __str__ Python 定义了__str__()和__repr__()两种方法,__str__()用于显示给...

  • __str__ & __repr__

    if you apply str or repr to an object, Python is looking ...

  • Python Day37

    python大大的图 str()&repr() 函数str() 用于将值转化为适于人阅读的形式,而repr()...

  • str和repr

    str和repr str适合人看,人看字符串'abc',就是一串字符abc repr适合机器看,机器看字符串‘ab...

  • python 中的__str__ 和__repr__方法

    看下面的例子就明白了 repr和str这两个方法都是用于显示的,str是面向用户的,而repr面向程序员。 打印操...

  • python12——包装标准类

    item系列 Str 和 Repr

网友评论

      本文标题:python里面的str和repr

      本文链接:https://www.haomeiwen.com/subject/ssshdxtx.html