简体   繁体   English

用更复杂的类型替换内置类型。 蟒蛇

[英]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派生,并实现adddiscard

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM