Python - AI 助手

Python collections.UserDict



Python 的UserDict()是collections模块中提供的字典类。它是一个类,充当字典对象的包装器。当想要创建具有某些修改功能或新功能的自定义字典时,此类非常有用。

可以将其视为向字典添加新行为。此类将字典实例作为参数,并模拟存储在常规字典中的字典。可以通过此类的data属性访问字典。

语法

以下是 Python UserDict()的语法:

collection.UserDict([data])

参数

它接受字典作为参数。

返回值

此类返回<class 'collections.UserDict'>对象。

示例

以下是 Python Userdict()类的基本示例:

from collections import UserDict
dic = {'a':1,'b': 2,'c': 3,'d':4}
# Creating an UserDict
userD = UserDict(dic)
print(userD)

以下是上述代码的输出:

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

继承 Userdict

我们可以继承Userdict()的属性,并在类中添加新函数,还可以修改现有方法。

示例

这里,我们创建了一个名为MyDict的类,并继承了Userdict类的属性。修改了一些方法,并添加了新方法:

# 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
dict = MyDict({'a':1,'b': 2,'c': 3})
print("Original Dictionary :", dict)
dict.pop(1)

以下是上述代码的输出:

Original Dictionary : {'a': 1, 'b': 2, 'c': 3}
Traceback (most recent call last):
  File "/home/cg/root/43843/main.py", line 30, in <module>
    dict.pop(1)
  File "/home/cg/root/43843/main.py", line 20, in pop
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Exception ignored in: <function MyDict.__del__ at 0x7f2456043880>
Traceback (most recent call last):
  File "/home/cg/root/43843/main.py", line 15, in __del__
RuntimeError: Deletion not allowed
python_modules.htm
广告

© . All rights reserved.