python __str__repr__ 区别

 

__str__

__repr__

两个内置函数都是调试常用的函数, 对象直接调用时会调用 __repr__的内容, __str__需要print一下对象才可以

两个函数的内容有时会写成相同内容   __repr__ = __str__

>>> class Test(object):
...     def __init__(self, value='hello world!'):
...         self.data = value
...         
...         
>>> class TestRepr(Test):
...     def __str__(self):
...         return "TestRepr(%s)--str" %self.data
...     def __repr__(self):
...         return "TestRepr(%s)--repr" %self.data
...     
>>> test = TestRepr()
>>> test
TestRepr(hello world!)--repr
>>> print test
TestRepr(hello world!)--str

 

posted @ 2019-03-11 15:05  布朗  阅读(157)  评论(0编辑  收藏  举报