__str__在python文档中的形貌以下”Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from repr() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.”
__repr__和__str__的区分(官方)
官方文档中str()中形貌了__repr__和__str__的区分:”Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ”.”,也就是__str__和__repr__区分在于__str__目标不在于老是尝试返回一个适用于eval()的字符串,而是返回一个很好地向人形貌对象的字符串。而__repr__目标在于”makes an attempt to return a string that would yield an object with the same value when passed to eval()”,尝试让返回的字符串能够经由过程eval()来生成一个一样的对象。
__repr__和__str__的区分(诠释)
__repr__和__str__这两个要领都是用于显现的,__str__是面向用户的,而__repr__面向程序员。
打印操纵会首先尝试__str__和str内置函数(print运转的内部等价情势),它一般应当返回一个友爱的显现。
__repr__用于一切其他的环境中:用于交互形式下提醒回应以及repr函数,假如没有运用__str__,会运用print和str。它一般应当返回一个编码字符串,能够用来从新建立对象,或许给开辟者细致的显现。
当我们想一切环境下都统一显现的话,能够重构__repr__要领;当我们想在差别环境下支撑差别的显现,比方终端用户显现运用__str__,而程序员在开辟时期则运用底层的__repr__来显现,实际上__str__只是覆盖了__repr__以获得更友爱的用户显现。
class Test(object): def __init__(self, value='hello, world!'): self.data = value >>> t = Test() >>> t <__main__.Test at 0x7fa91c307190> >>> print t <__main__.Test object at 0x7fa91c307190> # 看到了么?上面打印类对象并非很友爱,显现的是对象的内存地址 # 下面我们重构下该类的__repr__以及__str__,看看它们俩有啥区分 # 重构__repr__ class TestRepr(Test): def __repr__(self): return 'TestRepr(%s)' % self.data >>> tr = TestRepr() >>> tr 直接终端显现,不print就是面向程序员 TestRepr(hello, world!) >>> print tr print是面向程序员 TestRepr(hello, world!) # 重构__repr__要领后,不论直接输出对象照样经由过程print打印的信息都按我们__repr__要领中定义的花样举行显现了 # 重构__str__ calss TestStr(Test): def __str__(self): return '[Value: %s]' % self.data >>> ts = TestStr() >>> ts <__main__.TestStr at 0x7fa91c314e50> >>> print ts [Value: hello, world!] # 你会发明,直接输出对象ts时并没有按我们__str__要领中定义的花样举行输出,而用print输出的信息却改变了
以上就是__str__和repr__的区分的细致内容,更多请关注ki4网别的相干文章!