📜  Python中的 Collections.UserList

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

Python中的 Collections.UserList

Python列表是类似数组的数据结构,但不像它可以是同质的。单个列表可能包含数据类型,如整数、字符串以及对象。 Python中的列表是有序的并且有明确的计数。列表中的元素按照一定的顺序进行索引,列表的索引以 0 为第一个索引。
注意:更多信息请参考Python列表

Collections.UserList

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

collections.UserList([list])

示例 1:

Python3
# Python program to demonstrate
# userlist
 
 
from collections import UserList
 
 
L = [1, 2, 3, 4]
 
# Creating a userlist
userL = UserList(L)
print(userL.data)
 
 
# Creating empty userlist
userL = UserList()
print(userL.data)


Python3
# Python program to demonstrate
# 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
L = MyList([1, 2, 3, 4])
 
print("Original List")
 
# Inserting to List"
L.append(5)
print("After Insertion")
print(L)
 
# Deleting From List
L.remove()


输出:

[1, 2, 3, 4]
[]

示例 2:

Python3

# Python program to demonstrate
# 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
L = MyList([1, 2, 3, 4])
 
print("Original List")
 
# Inserting to List"
L.append(5)
print("After Insertion")
print(L)
 
# Deleting From List
L.remove()

输出:

Original List
After Insertion
[1, 2, 3, 4, 5]

Traceback (most recent call last):
  File "/home/9399c9e865a7493dce58e88571472d23.py", line 33, in 
    L.remove()
  File "/home/9399c9e865a7493dce58e88571472d23.py", line 15, in remove
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed