Alexander Oh
Alexander Oh

Reputation: 25601

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. Inheritance must not be used because some functions are removed to trigger method not found exceptions. This class is also used to find places where there might be implicit type conversions of the built-in python collection types.

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.

How can I create a constructor that behaves exactly like the built-in set?

Thus it must allow

Upvotes: 0

Views: 112

Answers (3)

yurib
yurib

Reputation: 8147

if you want to have an empty constructor...

class SetFacade:

def __init__(self, iterable=None):
    if iterable is None: 
         iterable = []
    self.lst = list(iterable)

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363487

Define exactly...

The best way to create a set-like class is to derive from collections.Set. You'll need to implement __len__, __iter__ and __contains__.

To be able to add element, derive from collections.MutableSet instead and implement add and discard.

Upvotes: 4

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29707

Inherit from set:

>>> class SetFacade(set):
...     pass
...
>>> SetFacade([1,2,3,4])
SetFacade([1, 2, 3, 4])
>>> SetFacade([1,2,3,3])
SetFacade([1, 2, 3]

Upvotes: 2

Related Questions