[Tutor] How to load a dict into a dict subclass?
Alan Gauld
alan.gauld at btinternet.com
Tue Oct 27 18:45:41 CET 2009
"John" <jfabiani at yolo.com> wrote
>> > >>> class Bar(dict):
>> > >>> pass
>> > >>>
>> > >>> foo = {'a':100, 'b':200, 'c': 300}
>> > >>> myvar = Bar()
>> > >>> myvar.update(foo)
>> > >>> myvar
>> >
>> > {'a': 100, 'c': 300, 'b': 200}
>
> Hey guru's could one of you explain why such a subclass is needed. How
> would
> it be used. I'm not sure but does not the deepcopy() work as above?
This particular subclass does nothing different to the normal dict so its
never needed. But it's only a demo of how to use the standard dict
methods in a subclass.
In general you might subclass a dict if you wanted to change the
behaviour of some specific method, or maybe add some new methods.
Or maybe you wanted a dictionary that could take a list as a key...
or even take a list of keys and return a list of values.
Lots of reasons for wanting to modify the standard dict behaviour.
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list