Reputation: 25601
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
SetFacade([a,c,b])
SetFacade([])
SetFacade()
Upvotes: 0
Views: 112
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
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
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