Class or Dictionary?
jeanmichel at sequans.com
Fri Feb 11 15:01:48 EST 2011
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
Using classes is the best choice.
However, if because there would be too much classes to define so that
you are forced to use your EmptyObject trick, adding attributes to the
inntance dynamically, I'd say that dictionnaries are a more common pattern.
Ideally, you would have something like:
def fromFile(cls, filename):
# example of abstract method
self.cat = None
self.elephant = None
self.banana = None
self.apple = None
Then you would have to write 100 PriceHolder subclasses...
More information about the Python-list