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
廣告