Class or Dictionary?

Martin De Kauwe mdekauwe at gmail.com
Fri Feb 11 17:01:40 CET 2011


On Feb 12, 2:40 am, Andrea Crotti <andrea.crott... at gmail.com> wrote:
> On Feb 11, 3:56 pm, Martin De Kauwe <mdeka... at gmail.com> 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
>
> Visually neater is not really a good parameter to judge.

Yes and No. Makes the code easier to read and less picky to type out,
in my opinion! But regarding the "no" that is why I posted the
question

> And in a class you can also overload __getattr__ to get the same
> syntax as a dictionary.
> But (>100) parameters seems really a lot, are you sure you can't split
> in many classes instead?

i have a number some are smaller, for example switch/control flags.
But the rest can be quite large. I can split them but I don't see the
advantage particularly. Currently by using them (e.g.
params.rate_of_decomp) it clearly distinguishes in the code this was a
model parameter read in from a file. I could create more categories
but it just means more names to remember and change in the code.

>
> Classes have also the advantage that you can do many things behind the
> scenes, while with plain dictionaries you can't do much...
> Where do you take those parameters from and what are they used for?

I have a big model which calculates a process, but this is made up of
a number of smaller models. I have coded each of these are separate
classes which expect to receive an object e.g. params, or two objects
e.g. params and switches.

thanks



More information about the Python-list mailing list