📜  Python中的 Collections.UserDict

📅  最后修改于: 2022-05-13 01:55:26.670000             🧑  作者: Mango

Python中的 Collections.UserDict

用于存储数据值(如地图)的无序数据值集合在Python中称为 Dictionary 。与仅将单个值作为元素保存的其他数据类型不同,Dictionary 保存键:值对。字典中提供了键值,使其更加优化。

注意:更多信息请参考Python字典

Collections.UserDict

Python支持字典,例如集合模块中存在的名为UserDict的容器。此类充当字典对象的包装类。当人们想要创建自己的具有一些修改功能或一些新功能的字典时,此类很有用。它可以被认为是向字典中添加新行为的一种方式。此类将字典实例作为参数,并模拟保存在常规字典中的字典。该字典可通过此类的数据属性访问。

句法:

collections.UserDict([initialdata])

示例 1:

Python3
# Python program to demonstrate
# userdict
 
 
from collections import UserDict
 
 
d = {'a':1,
    'b': 2,
    'c': 3}
 
# Creating an UserDict
userD = UserDict(d)
print(userD.data)
 
 
# Creating an empty UserDict
userD = UserDict()
print(userD.data)


Python3
# Python program to demonstrate
# userdict
  
 
from collections import UserDict
  
 
# Creating a Dictionary where
# deletion is not allowed
class MyDict(UserDict):
     
    # Function to stop deletion
    # from dictionary
    def __del__(self):
        raise RuntimeError("Deletion not allowed")
         
    # Function to stop pop from
    # dictionary
    def pop(self, s = None):
        raise RuntimeError("Deletion not allowed")
         
    # Function to stop popitem
    # from Dictionary
    def popitem(self, s = None):
        raise RuntimeError("Deletion not allowed")
     
# Driver's code
d = MyDict({'a':1,
    'b': 2,
    'c': 3})
 
print("Original Dictionary")
print(d)
 
d.pop(1)


输出:

{'a': 1, 'b': 2, 'c': 3}
{}

示例 2:让我们创建一个继承自 UserDict 的类来实现自定义字典。

Python3

# Python program to demonstrate
# userdict
  
 
from collections import UserDict
  
 
# Creating a Dictionary where
# deletion is not allowed
class MyDict(UserDict):
     
    # Function to stop deletion
    # from dictionary
    def __del__(self):
        raise RuntimeError("Deletion not allowed")
         
    # Function to stop pop from
    # dictionary
    def pop(self, s = None):
        raise RuntimeError("Deletion not allowed")
         
    # Function to stop popitem
    # from Dictionary
    def popitem(self, s = None):
        raise RuntimeError("Deletion not allowed")
     
# Driver's code
d = MyDict({'a':1,
    'b': 2,
    'c': 3})
 
print("Original Dictionary")
print(d)
 
d.pop(1)

输出:

Original Dictionary
{'a': 1, 'c': 3, 'b': 2}
Traceback (most recent call last):
  File "/home/3ce2f334f5d25a3e24d10d567c705ce6.py", line 35, in 
    d.pop(1)
  File "/home/3ce2f334f5d25a3e24d10d567c705ce6.py", line 20, in pop
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Exception ignored in: 
Traceback (most recent call last):
  File "/home/3ce2f334f5d25a3e24d10d567c705ce6.py", line 15, in __del__
RuntimeError: Deletion not allowed