Differences between Class(Object) and Class(Dict) for dictionary usage?

Ian Kelly ian.g.kelly at gmail.com
Wed Apr 27 10:24:02 EDT 2016


On Tue, Apr 26, 2016 at 11:31 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 04/26/2016 08:43 PM, Christopher Reimer wrote:
>
>> If I'm using a dictionary to store variables for an object, and
>> accessing the variable values from dictionary via property decorators,
>> would it be better to derive the class from object or dict?
>>
>>      class Test1(object):
>>          def __init__(self):
>>              self.state = {'key': 'value'}
>>
>> Or:
>>
>>      class Test2(dict):
>>          def __init__(self):
>>                  self.__dict__ = {'key', 'value'}
>>
>> I haven't seen a good pro/con discussion on the Internet for using one
>> over the other. I played with both in my code. Doesn't seem to make a
>> great difference either way. Using object seems to be the most simplest
>> approach.
>
>
> Using a dict gets you a bunch of methods for free: keys(), values(),
> items(), get(), etc., etc..

You get those for free either way; in the first case you just have use
self.state.keys() instead of self.keys().

The question boils down to composition versus inheritance, and the
prevailing wisdom is to prefer composition. For me the discerning test
is "do the things that are in this dict make sense as items contained
by my object?" If the answer is yes, then go ahead and subclass from
dict. More often, the answer is no.

Some other great questions to ask yourself are "do I really want
len(my_object) to return the number of items in this dict" and "do I
really want list(my_object) to return all the keys in this dict"? If
the answer to all those is yes, then it's probably fair to say that
your object is-a dict and should be modeled as such.



More information about the Python-list mailing list