1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 # 不建议继承list和dict 4 from collections import UserDict 5 from collections import defaultdict 6 7 8 class MyDict1(dict): 9 def __setitem__(self, key, value): 10 super().__setitem__(key, value*2) 11 12 13 my_dict1 = MyDict1(one=1) 14 print(my_dict1) 15 my_dict1['one'] = 1 16 print(my_dict1) 17 18 # 建议继承UserDict 19 20 21 class MyDict2(UserDict): 22 def __setitem__(self, key, value): 23 super().__setitem__(key, value*2) 24 25 26 my_dict2 = MyDict2(one=1) 27 print(my_dict2) 28 29 # defaultdict 30 my_dict3 = defaultdict(dict) 31 value = my_dict3['one'] 32 print(my_dict3)
{'one': 1} {'one': 2} {'one': 2} defaultdict(<class 'dict'>, {'one': {}})