对象转字典列表&&字典转对象

import os
class Student:
    stu_list = []
    def __init__(self, name, age, phone):
        self.name = name
        self.age = age
        self.phone = phone
    def __str__(self):
        return f'{self.name}, {self.age}, {self.phone}'


if __name__ == '__main__':
    s1 = Student('张三', 20, '555')
    s2 = Student('李思思', 18, '666')
    Student.stu_list.append(s1)
    Student.stu_list.append(s2)
    stu_dict = [s.__dict__ for s in Student.stu_list] # 推导式:对象转字典列表

    stu_list = [Student(**s) for s in stu_dict]
    print(stu_dict)
    print(stu_list)

image

 

posted @ 2025-11-12 14:25  iTao0128  阅读(4)  评论(0)    收藏  举报