Loading... 对象的__dict__方法只能将实例变量转换成字典,不能将类变量转换成字典。 将Python中的对象中的属性转换成字典方法: 1.需要先实现类变量里面的keys方法,返回值为要转换的变量名称(列表形式或者元组形式) 2.实现__getitem__方法,实现这个方法后,类可以使用 类名[属性名] 这种方式获取属性是值 3.使用dict(类名) 来转换成字典 ```python class People(object): name = "liaokong" age = 18 def __init__(self): self.gender = "male" def keys(self): return "name", "age", "gender" def __getitem__(self, item): return getattr(self, item) p = People() print(dict(p)) ``` Last modification:April 8th, 2019 at 11:21 pm © 允许规范转载 Support If you think my article is useful to you, please feel free to appreciate ×Close Appreciate the author Sweeping payments