Friday, 23 August 2013

extending built-in python dict class

extending built-in python dict class

I want to create a class that would extend dict's functionalities. This is
my code so far:
class Masks(dict):
def __init__(self, positive=[], negative=[]):
self['positive'] = positive
self['negative'] = negative
I want to have two predefined arguments in the constructor: a list of
positive and negative masks. When I execute the following code, I can run
m = Masks()
and a new masks-dictionary object is created - that's fine. But I'd like
to be able to create this masks objects just like I can with dicts:
d = dict(one=1, two=2)
But this fails with Masks:
>>> n = Masks(one=1, two=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 'two'
I should call the parent constructor init somewhere in Masks.init
probably. I tried it with **kwargs and passing them into the parent
constructor, but still - something went wrong. Could someone point me on
what should I add here?

No comments:

Post a Comment