python __dict__ 操作姿势
1,__dict__能做什么
类的__dict__属性和类对象的__dict__属性(大白话:将类中的属性以键值对得方式输出,type是dict类型)
案例:
class A:
def __init__(self, name, age):
self.name = name
self.age = age
def Aa(self):
return self.__dict__
aa = A('张三', 30)
print(aa.Aa())
结果:
{'name': '张三', 'age': 30}
解释:其实是将类中得属性通过键值对得方式输出(dict)
2,__dict__批量处理数据返回dict类型
案例:
class A():
def __init__(self, dicts):
self.__dict__.update(dicts)
print(self.__dict__)
if __name__ == '__main__':
dicts = {"name": "lisa", "age": 23, "sex": "women", "hobby": "hardstyle"}
a = A(dicts)
结果:
{'name': 'lisa', 'age': 23, 'sex': 'women', 'hobby': 'hardstyle'}