温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么对齐打印对象属性

发布时间:2021-06-21 16:38:22 来源:亿速云 阅读:159 作者:Leah 栏目:大数据

Python中怎么对齐打印对象属性,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

对齐打印对象属性

print 输出对象 dict 全挤在一行,很难看。因此希望输出类似 json 对齐的方式。

基本的思想是转成 json 格式再输出。随便一搜,找到如下代码,普通情况下可用:

def obj_to_json():
    stu = Student(28, 'male', '13000000000', '123@qq.com')
    print(type(stu))  # <class 'json_test.student.Student'>
    print(stu)
    stu = stu.__dict__  # 将对象转成dict字典
    print(type(stu))  # <class 'dict'>
    print(stu)
    j = json.dumps(obj=stu, indent=4)
    print(j)

但有些对象中会包含一些特殊属性,如另外一个对象,则用此法会报错:

TypeError: Object of type xxx is not JSON serializable

其实就是 JSON 不支持这种对象。我们可以自定义处理特殊对象的方法,完整代码如下:

# encoding:utf-8
# author: over

import json
from datetime import datetime, date

class Student(object):
    def __init__(self, age, sex, mobile, date):
            self.age = age
            self.sex = sex
            self.mobile = mobile
            self.date = date

# 扩展 json 无法解析的类型
class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            # return obj.strftime('%Y-%m-%d %H:%M:%S')
            return str(obj)
        elif isinstance(obj, date):
            # return obj.strftime('%Y-%m-%d')
            return str(obj)
        else:
            try:
                return json.JSONEncoder.default(self, obj)
            except Exception as e:
                print('type not support: '+str(obj))
                # 默认的处理不了直接强转字符串
                return str(obj)

# json 对齐方式输出对象所有属性,方便查看
def printJson(obj):
    if hasattr(obj,'__dict__'):
        obj = obj.__dict__

    # ensure_ascii=False 中文不变成百分符
    # indent 缩进行增加的空格数
    j = json.dumps(obj, cls=ComplexEncoder, ensure_ascii=False, indent=4)
    print(j)

if __name__ == '__main__':
    stu = Student(28, 'male', '13000000000', datetime.now())
    printJson(stu)

输出:

{
    "age": 28,
    "sex": "male",
    "mobile": "13000000000",
    "date": "2019-07-07 14:43:51.466416"
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI