Class or Dictionary?
subscriptions at cagttraining.com
Fri Feb 11 12:02:08 EST 2011
From an old-time Smalltalker / object guy, take this for whatever it's worth.
The *primary* reason for going with a class over a dictionary is if there is specific behavior that goes along with these attributes.
If there isn't, if this is "just" an 'object store', there's no reason not to use a dictionary.
After all, it is not too far off the mark to say a class is just a dictionary with it's own behavior set...
As another poster pointed out, 100 (or more) attributes is an oddity, I would call it a 'code smell'. Whereas a dictionary with 100 entries is no big deal at all.
But for me, the big deciding factor comes down to whether or not there is specific behavior associated with this "bundle" of attributes. If yes, class, if no, nothing wrong with dictionary.
On Feb 11, 2011, at 9:56 AM, Martin De Kauwe wrote:
> I have a series of parameter values which i need to pass throughout my
> code (>100), in C I would use a structure for example. However in
> python it is not clear to me if it would be better to use a dictionary
> or build a class object? Personally I think accessing the values is
> neater (visually) with an object rather than a dictionary, e.g.
> x = params['price_of_cats'] * params['price_of_elephants']
> x = params.price_of_cats * params.price_of_elephants
> So currently I am building a series of class objects to hold different
> parameters and then passing these through my code, e.g.
> class EmptyObject:
> self.animal_prices = EmptyObject()
> self.price_of_cats = 12 or reading a file and populating the object
> I would be keen to hear any reasons why this is a bad approach (if it
> is, I haven't managed to work this out)? Or perhaps there is a better
More information about the Python-list