python对象转字典,,详细如下: 1 cl


详细如下:

 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 s11 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对象转字典

评论关闭