当前位置:首页 > Python教程 > python技巧

python对象转字典

详细如下:

             1
            class
             TestDict:

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

 

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


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐