• 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__。

  • 相关阅读:
    (打包报错)AS打包报错:Generate Signed APK: Errors while building APK. You can find the errors in the 'Messages' view.
    NABCD
    石家庄地铁站项目最终总结报告
    团队冲刺2.7
    团队冲刺2.6
    团队冲刺2.5
    团队冲刺2.4
    团队冲刺2.3
    用户体验评价——win10自带微软拼音输入法
    团队冲刺2.2
  • 原文地址:https://www.cnblogs.com/CGAlpha/p/6913661.html
Copyright © 2020-2023  润新知