zoukankan      html  css  js  c++  java
  • python class对象转换成json/字典

    # -*- encoding: UTF-8 -*-
    
    class Student:
        name = ''
        age = 0
        
        def __init__(self, name, age):
            self.name = name
            self.age = age
        
    
    def convert_to_dict(obj):
        '''把Object对象转换成Dict对象'''
        dict = {}
        dict.update(obj.__dict__)
        return dict
          
            
    def convert_to_dicts(objs):
        '''把对象列表转换为字典列表'''
        obj_arr = []
        
        for o in objs:
            #把Object对象转换成Dict对象
            dict = {}
            dict.update(o.__dict__)
            obj_arr.append(dict)
        
        return obj_arr
              
    
    def class_to_dict(obj):
        '''把对象(支持单个对象、list、set)转换成字典'''
        is_list = obj.__class__ == [].__class__
        is_set = obj.__class__ == set().__class__
        
        if is_list or is_set:
            obj_arr = []
            for o in obj:
                #把Object对象转换成Dict对象
                dict = {}
                dict.update(o.__dict__)
                obj_arr.append(dict)
            return obj_arr
        else:
            dict = {}
            dict.update(obj.__dict__)
            return dict
       
    stu = Student('zhangsan', 20)
    
    print '-----------'
    print convert_to_dict(stu)
     
    print '-----------'
    print convert_to_dicts([stu, stu]) 
    
    print '-----------'
    print class_to_dict(stu)
    
    print '-----------'
    print class_to_dict([stu, stu])
    
    stua = Student('zhangsan', 20)
    stub = Student('lisi', 10)
    
    stu_set = set()
    stu_set.add(stua)
    stu_set.add(stub)
    print class_to_dict(stu_set)
    

      

  • 相关阅读:
    k3sk8s集群-node节点设置不可调度或者删除node节点
    CentOS8防暴力破解fail2ban
    网站挂马情况处理
    linux给普通用户赋予sudo权限免密码
    Mockito (二十四)
    Mockito (二十三)
    Mockito (二十二)
    Mockito (二十一)
    Mockito (二十)
    Mockito (十九)
  • 原文地址:https://www.cnblogs.com/linjiqin/p/4363592.html
Copyright © 2011-2022 走看看