Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #107724 > unrolled thread
| Started by | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| First post | 2016-04-27 08:24 -0600 |
| Last post | 2016-04-27 08:24 -0600 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Differences between Class(Object) and Class(Dict) for dictionary usage? Ian Kelly <ian.g.kelly@gmail.com> - 2016-04-27 08:24 -0600
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2016-04-27 08:24 -0600 |
| Subject | Re: Differences between Class(Object) and Class(Dict) for dictionary usage? |
| Message-ID | <mailman.148.1461767085.32212.python-list@python.org> |
On Tue, Apr 26, 2016 at 11:31 PM, Ethan Furman <ethan@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.
Back to top | Article view | comp.lang.python
csiph-web