首页 > 编程语言 > 详细

python对象转字典

时间:2018-10-26 18:45:17      阅读:174      评论:0      收藏:0      [点我收藏+]

详细如下:

 1 class TestDict:
 2     name = "wyb"
 3     age = "21"
 4 
 5     def __init__(self):
 6         self.gender = male
 7 
 8     def keys(self):                         # 获取字典的键
 9         s = (name, age, gender)
10         return s
11 
12     def __getitem__(self, item):            # 获取键对应的值
13         return getattr(self, item)          # getattr获取对象下某个属性的值
14 
15 
16 o = TestDict()
17 print(dict(o))          # 创建字典 -> 先调用对象下的keys方法再用o["xxx"]获取值([]本质上是调用对象下的__getitem__方法)

 

python对象转字典

原文:https://www.cnblogs.com/wyb666/p/9857678.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!