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

猜你喜欢

转载自www.cnblogs.com/brownz/p/10510670.html