python里面的str和repr

2017-08-21  本文已影响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__是保证对象的准确性,让程序员处理对象的时候更加精确。

上一篇 下一篇

猜你喜欢

热点阅读