python里面的str和repr

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__是保证对象的准确性,让程序员处理对象的时候更加精确。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容