[英]Replacing built-in types with more complex types. Python
I want to create a replacement class of the built-in type set
that can be constructed exactly like set. 我想创建一个内置类型
set
的替换类,它可以像set一样构造。 Inheritance must not be used because some functions are removed to trigger method not found
exceptions. 不得使用继承,因为已删除某些函数以触发
method not found
异常。 This class is also used to find places where there might be implicit type conversions of the built-in python collection types. 此类还用于查找可能存在内置python集合类型的隐式类型转换的位置。
class SetFacade:
def __init__(self, iterable):
self.lst = list(iterable)
# other allowed member functions...
The problem with this constructor definition is, that I cant call the constructor SetFacade()
without arguments. 此构造函数定义的问题是,我不能在没有参数的情况下调用构造函数
SetFacade()
。
How can I create a constructor that behaves exactly like the built-in set? 如何创建行为与内置集合完全相同的构造函数?
Thus it must allow 因此,它必须允许
SetFacade([a,c,b])
SetFacade([])
SetFacade()
Define exactly ... 准确定义...
The best way to create a set-like class is to derive from collections.Set
. 创建类似集合的类的最好方法是从
collections.Set
派生。 You'll need to implement __len__
, __iter__
and __contains__
. 您需要实现
__len__
__iter__
, __iter__
和__contains__
。
To be able to add element, derive from collections.MutableSet
instead and implement add
and discard
. 为了能够添加元素,请从
collections.MutableSet
派生,并实现add
和discard
。
Inherit from set
: 从
set
继承:
>>> class SetFacade(set):
... pass
...
>>> SetFacade([1,2,3,4])
SetFacade([1, 2, 3, 4])
>>> SetFacade([1,2,3,3])
SetFacade([1, 2, 3]
if you want to have an empty constructor... 如果您想要一个空的构造函数...
class SetFacade:
def __init__(self, iterable=None):
if iterable is None:
iterable = []
self.lst = list(iterable)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.