Class or Dictionary?

Jean-Michel Pichavant jeanmichel at
Fri Feb 11 15:01:48 EST 2011

Martin De Kauwe wrote:
> Hi,
> 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']
> vs.
> 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:
>     pass
> 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
> one?
> thanks
> Martin
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:

class PriceHolder(object):
    def fromFile(cls, filename):
       # example of abstract method

class Animals(PriceHolder):
    def __init__(self): = None
       self.elephant = None

class Fruits(PriceHolder):
    def __init__(self):
       self.banana = None = None

Then you would have to write 100 PriceHolder subclasses...


More information about the Python-list mailing list