再见,print

作者: Python技术提升 | 来源:发表于2020-05-27 20:41 被阅读0次

    学python学到的第一个函数就是print

    print("hello world")
    

    不管是新手还是老手,都会经常用来调试代码。但是对于稍微复杂的对象,打印出来就的时候可读性就没那么好了。

    例如:

    >>> coordinates = [
    ...    {
    ...        "name": "Location 1",
    ...        "gps": (29.008966, 111.573724)
    ...    },
    ...    {
    ...        "name": "Location 2",
    ...        "gps": (40.1632626, 44.2935926)
    ...    },
    ...    {
    ...        "name": "Location 3",
    ...        "gps": (29.476705, 121.869339)
    ...    }
    ... ]
    
    >>> print(coordinates)
    [{'name': 'Location 1', 'gps': (29.008966, 111.573724)}, {'name': 'Location 2', 'gps': (40.1632626, 44.2935926)}, {'name': 'Location 3', 'gps': (29.476705, 121.869339)}]
    >>>
    

    打印一个很长的列表时,全部显示在一行,两个屏幕都装不下。

    于是 pprint 出现了

    pprint

    pprint 的全称是Pretty Printer,更美观的 printer。在打印内容很长的对象时,它能够以一种格式化的形式输出。

    >>> import pprint
    >>> pprint.pprint(coordinates)
    [{'gps': (29.008966, 111.573724), 'name': 'Location 1'},
     {'gps': (40.1632626, 44.2935926), 'name': 'Location 2'},
     {'gps': (29.476705, 121.869339), 'name': 'Location 3'}]
    >>>
    

    当然,你还可以自定义输出格式

    # 指定缩进和宽度
    >>> pp = pprint.PrettyPrinter(indent=4, width=50)
    >>> pp.pprint(coordinates)
    [   {   'gps': (29.008966, 111.573724),
            'name': 'Location 1'},
        {   'gps': (40.1632626, 44.2935926),
            'name': 'Location 2'},
        {   'gps': (29.476705, 121.869339),
            'name': 'Location 3'}]
    

    但是pprint还不是很优雅,因为打印自定义的类时,输出的是对象的内存地址相关的一个字符串

    class Person():
        def __init__(self, age):
            self.age = age
    
    p = Person(10)
    
    >>> print(p)
    <__main__.Person object at 0x00BCEBD0>
    >>> import pprint
    >>> pprint.pprint(p)
    <__main__.Person object at 0x00BCEBD0>
    

    beeprint

    而用beeprint可以直接打印对象里面的属性值,省去了重写 str 方法的麻烦

    from beeprint import pp
    pp(p)
    instance(Person):
      age: 10
    

    不同的是,print和pprint是python的内置模块,而 beeprint 需要额外安装。

    相关文章

      网友评论

        本文标题:再见,print

        本文链接:https://www.haomeiwen.com/subject/ptbgahtx.html