为什么python不提供UserSet
类来扩展和定义用户定义的集合。它确实提供了 UserDict
, UserList
, UserString
但没有UserSet
.
我指的是Python Documentation
最佳答案
PEP 3108提供了一些关于为什么没有 UserSet
的见解或类似的实现以类似的方式添加到 UserDict
之类的。
Guido pronounced that "silly old stuff" is to be deleted from the stdlib for Py3K. This is open-ended on purpose. Each module to be removed needs to have a justification as to why it should no longer be distributed with Python.
UserDict
, UserList
, 和 UserString
都列在 PEP 3108 的“过时”部分,并注明以下原因,并表明它们已移至 collections
模块。Not as useful since types can be a superclass
鉴于它们被认为是“过时的”,因此没有为其他类型(例如 sets)实现类似的类也就不足为奇了。 .
由于类型可以是父类(super class),而抽象基类为创建各种集合、序列、映射和其他类型的子类提供了合理的替代方案,这些类型具有通过扩展内置类型本身难以实现的重大变化,因此似乎没有必要包含
collections.abc
中已经提供的每种类型的这些“入门”类.以下是
UserSet
的一个非常基本的实现与 data
将类的内容存储在真实的 set
中的属性(类似于 UserDict
等所采用的方法)。虽然在标准库中包含这样的实现可能对您很有用,但您自己实现并不是非常困难(并且如果对某人可能“有用”的所有内容都包含在标准库中,那么 Python 将变得非常臃肿)。from collections.abc import Hashable, MutableSet
class UserSet(Hashable, MutableSet):
__hash__ = MutableSet._hash
def __init__(self, iterable=()):
self.data = set(iterable)
def __contains__(self, value):
return value in self.data
def __iter__(self):
return iter(self.data)
def __len__(self):
return len(self.data)
def __repr__(self):
return repr(self.data)
def add(self, item):
self.data.add(item)
def discard(self, item):
self.data.discard(item)
s = UserSet([1,1,2,3])
print(s)
# {1, 2, 3}
关于python - 为什么 Python 中没有定义 UserSet 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132624/