zoukankan      html  css  js  c++  java
  • Python str & repr

    Python str & repr

    repr 更多是用来配合 eval 的 (<- 点击查看),str 更多是用来转换成字符串格式的

    str() & repr()

    str() 和 repr() 都会返回一个字符串
    但是 str() 返回的结果更加适合于人阅读,repr() 返回的结果更适合解释器读取

    两者差异

    示例:

    string = 'Hello World'
    print(str(string), len(str(string)))
    print(repr(string), len(repr(string)))
    

    输出结果:

    Hello World 11
    'Hello World' 13
    

    说明 str() 返回的仍然是字符串本身,但是 repr() 返回的是带引号的字符串

    __repr__ & __str__

    在一个类中 __repr____str__ 都可以返回一个字符串

    示例:
    当类中同时有这两个方法

    class Test(object):
        def __init__(self):
            pass
    
        def __repr__(self):
            return 'from repr'
    
        def __str__(self):
            return 'from str'
    
    
    test = Test()
    print(test)
    print(test.__repr__())
    print(test.__str__())
    

    输出结果:

    from str
    from repr
    from str
    

    当类中只有 __str__ 方法时

    class Test(object):
        def __init__(self):
            pass
    
        def __str__(self):
            return 'from str'
    
    
    test = Test()
    print(test)
    print(test.__repr__())
    print(test.__str__())
    

    输出结果:

    from str
    <__main__.Test object at 0x105df89e8>
    from str
    

    当类中只有 __repr__ 方法时

    class Test(object):
        def __init__(self):
            pass
    
        def __repr__(self):
            return 'from repr'
    
    
    test = Test()
    print(test)
    print(test.__repr__())
    print(test.__str__())
    

    输出结果:

    from repr
    from repr
    from repr
    

    说明 print() 函数调用的是 __str__ ,而命令行下直接输出时调用的是 __repr__
    当类中没有 __str__ 时,会调用 __repr__ ,但是如果没有 __repr__ ,并不会去调用 __str__

  • 相关阅读:
    java语言基础1问题汇总
    java从命令行接受多个数字求和输出
    关于Django迁移出现问题
    python中在ubuntu中安装虚拟环境及环境配置
    MVC与MVT
    前端性能优化
    less、sass、stylus
    bootstrap
    Swiper4.x使用方法
    swiper
  • 原文地址:https://www.cnblogs.com/dbf-/p/11609313.html
Copyright © 2011-2022 走看看