dictionary - extending built-in python dict class -
i want create class extend dict's functionalities. code far:
class masks(dict): def __init__(self, positive=[], negative=[]): self['positive'] = positive self['negative'] = negative i want have 2 predefined arguments in constructor: list of positive , negative masks. when execute following code, can run
m = masks() and new masks-dictionary object created - that's fine. i'd able create masks objects can dicts:
d = dict(one=1, two=2) but fails masks:
>>> n = masks(one=1, two=2) traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: __init__() got unexpected keyword argument 'two' i should call parent constructor init somewhere in masks.init probably. tried **kwargs , passing them parent constructor, still - went wrong. point me on should add here?
you must call superclass __init__ method. , if want able use masks(one=1, ..) syntax have use **kwargs:
in [1]: class masks(dict): ...: def __init__(self, positive=(), negative=(), **kwargs): ...: super(masks, self).__init__(**kwargs) ...: self['positive'] = list(positive) ...: self['negative'] = list(negative) ...: in [2]: m = masks(one=1, two=2) in [3]: m['one'] out[3]: 1 a general note: do not subclass built-ins!!! seems easy way extend them has lot of pitfalls will bite @ point.
a safer way extend built-in use delegation, gives better control on subclass behaviour , can avoid many pitfalls of inheriting built-ins. (note implementing __getattr__ it's possible avoid reimplementing explicitly many methods)
inheritance should used last resort when want pass object code explicit isinstance checks.
Comments
Post a Comment