Python - AI 助手

Python collections.UserList



Python 的 **UserList** 是 **collections** 模組中類似列表的容器。這個類充當列表物件的包裝器類。當想要建立具有某些修改後的功能或某些新功能的自己的列表時,它非常有用。可以將其視為為列表新增新功能的一種方法。

UserList() 接受列表例項作為引數,並模擬儲存在常規列表中的列表。可以透過此類的 data 屬性訪問該列表。

語法

以下是 Python **UserList** 類的語法:

collections.UserList(data)

引數

此類接受列表作為引數。

返回值

此類返回 **<class 'collections.UserList'>** 物件。

示例

以下是 Python **UserList()** 的基本示例:

# Python program to demonstrate
# userlist
from collections import UserList
List1 = [10, 20, 30, 40]
# Creating a userlist
userlist = UserList(List1)
print(userlist.data)

以上程式碼的輸出如下:

[10, 20, 30, 40]

繼承 UserList

我們可以將 **UserList** 的屬性繼承到另一個類中,並可以修改功能,並向類中新增新方法。

示例

在下面的示例中,我們繼承了 UserList 類並停用了刪除功能:

from collections import UserList
# Creating a List where
# deletion is not allowed
class MyList(UserList):
	
	# Function to stop deletion
	# from List
	def remove(self, s = None):
		raise RuntimeError("Deletion not allowed")
		
	# Function to stop pop from 
	# List
	def pop(self, s = None):
		raise RuntimeError("Deletion not allowed")
	
# Driver's code
list = MyList([11, 21, 31, 41])
print("Original List :",list)
# Inserting to List"
list.append(5)
print("After Insertion :", list)
# Deleting From List
list.remove()

以上程式碼的輸出如下:

Original List : [11, 21, 31, 41]
After Insertion : [11, 21, 31, 41, 5]
Traceback (most recent call last):
  File "/home/cg/root/88942/main.py", line 23, in <module>
    list.remove()
  File "/home/cg/root/88942/main.py", line 9, in remove
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
python_modules.htm
廣告