zoukankan      html  css  js  c++  java
  • Python进阶-----通过类的内置方法__str__和__repr__自定制输出(打印)对象时的字符串信息

    __str__方法其实是在print()对象时调用,所以可以自己定义str字符串显示信息,在该方法return一个字符串,如果不是字符串则报错
    print(obj) 等同于-->str(obj) 等同于-->obj.__str__

    #未自定__str__信息
    class Foo:
        def __init__(self,name,age):
            self.name = name
            self.age = age
    
    f = Foo('Menawey',24)
    print(f)   #<__main__.Foo object at 0x000002EFD3D264A8>  因为没有定制__str__,则按照默认输出
    
    #自定__str__信息
    class Foo:
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def __str__(self):
            return '名字是%s,年龄是%d'%(self.name,self.age)
    
    f1 = Foo('Meanwey',24)
    print(f1)           #名字是Meanwey,年龄是24
    s = str(f1)         #---> f1.__str__
    print(s)            #名字是Meanwey,年龄是24

    __repr__方法是在控制台直接输出一个对象信息或者print一个对象信息时调用,如果自定了__str__信息,print时默认执行__str__
    如果没有自定__str__,则print时执行__repr__

    #未自定__str__信息,自定了__repr__
    class Foo:
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def __repr__(self):
            return '来自repr-->名字是%s,年龄是%d'%(self.name,self.age)
    
    f2 = Foo('Meanwey',24)
    print(f2)               #来自repr-->名字是Meanwey,年龄是24   因为没有自定__str__,则执行__repr__
    
    #自定了__str__信息,自定了__repr__
    class Foo:
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def __str__(self):
            return '来自str-->名字是%s,年龄是%d'%(self.name,self.age)
    
        def __repr__(self):
            return '来自repr-->名字是%s,年龄是%d'%(self.name,self.age)
    
    f2 = Foo('Meanwey',24)
    print(f2)               #来自str-->名字是Meanwey,年龄是24   因为自定了__str__,则print时不会执行__repr__
  • 相关阅读:
    jvm理论-运行时数据区
    java nio-理解同步、异步,阻塞和非阻塞
    真正的mybatis_redis二级缓存
    扩展 DbUtility (1)
    DbUtility v3 背后的故事
    DbUtility v3
    Jumony Core 3,真正的HTML引擎,正式版发布
    新项目,WebTest
    面试经验总结,每个求职者应该具有的职业素养
    mkdir()提示No such file or directory错误的解决方法
  • 原文地址:https://www.cnblogs.com/Meanwey/p/9788843.html
Copyright © 2011-2022 走看看