python中dict.update与__dict__的使用

dict1.update(dict2) 方法

可使用一个字典dict2所包含的键值对来更新己有的字典dict1。

如果被更新的字典中己包含对应的键值对,那么原 value 会被覆盖;如果被更新的字典中不包含对应的键值对,则该键值对被添加进去。

a = {'one': 1, 'two': 2, 'three':3}
b = {'one': 100, 'four': 4}
a.update(b)
print(a)
{'one': 100, 'two': 2, 'three': 3, 'four': 4}

__dict__方法

__dict__是用来存储对象属性的一个字典,其键为属性名,值为属性的值。

class Test:
    def __init__(self):
        self.name = 'xiaoming'
        self.age = 18
        self.gender = 'man'
    abc = 666
    
    def print_dict(self):
        print(self.__dict__)

a = Test()
a.print_dict()
{'name': 'xiaoming', 'age': 18, 'gender': 'man'}

由上面这个例子可以看出,__dict__中存储了对象的属性

__dict__.update的使用

正常情况下,我们有一个字典,想通过字典的键值对构建一个类的属性,我们可以这样做

person_info = {'name': 'xiaoming','age': 18,'gender': 'man'}
class Person:
    def __init__(self, person_info):
        self.name = person_info.get('name')
        self.age = person_info.get('age')
        self.gender = person_info.get('gender')

        
a = Person(person_info)
print(a.age)
18

这种操作在数据量小的时候还可以实现,当数据量很大时(键值对为100个),如何还是这样一个一个赋值不敢想不敢想,人家都写完代码了,你还在赋值。。。

因此接下来我们需要通过__dict__.update来实现自动化实例变量

person_info = {'name': 'xiaoming','age': 18,'gender': 'man'}
class Person1:
    def __init__(self, person_info):
        self.__dict__.update(person_info)

        
b = Person1(person_info)
print(b.name)
xiaoming

这样的话就可以自动化实例变量,其中update方法与字典正常的update方法相同

参考文章:

  1. Python dict字典update()方法
  2. python魔法函数__dict__和__getattr__的妙用
posted @ 2021-02-27 15:49  zlbingo  阅读(197)  评论(0)    收藏  举报