Python __str__() and __repr()__

__str()是一个特殊的方法,可以把类变成实例。

import os,sys
class myTest(object):

    def __init__(self,strTmp=''):
        super(myTest, self).__init__()
        self.strTmp = strTmp
    def __str__(self):
        print 'this is str func!'
        return 'Class :' + myTest.__name__ + "->" + self.strTmp
if __name__=='__main__':
    tmp = myTest("wowo")
    print tmp
    print "_______________________________"
    tmp1 = myTest("ooxx")
    tmp
    print "_______________________________"

this is str func!
Class :myTest->wowo
_______________________________
_______________________________

Process finished with exit code 0

直接用tmp1的时候,是不会调用__str()__的

__repr()__ 是将一个对象转化为字符串显示,仅仅是显示。

object.__repr__(self): called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object.

object.__str__(self): called by the str() build-in function and by the print statement to compute the "informal" string representation of an object.

事实上,__str__是被print函数调用的,一般都是return一个什么东西。这个东西应该是以字符串的形式表现的。如果不是要用str()函数转换。当你打印一个类的时候,那么print首先调用的就是类里面的定义的__str__。

原文地址:https://www.cnblogs.com/CGAlpha/p/6913661.html