Class or Dictionary?

Martin De Kauwe mdekauwe at gmail.com
Mon Feb 14 02:33:40 CET 2011


On Feb 14, 12:02 pm, Terry Reedy <tjre... at udel.edu> wrote:
> On 2/13/2011 6:16 PM, Martin De Kauwe wrote:
>
>
>
>
>
> > I think I got it, did you mean something like this?
>
> > class Constants:
>
> >      radius_of_earth = 6.37122E+6
> >      days_as_yrs = 1.0 / 365.25
> >      m2_as_ha = 1E-4  # metres squared as hectares
> >      g_as_tonnes = 1E-6  # grammes as tonnes
> >      kg_as_tonnes = 1E-3  # kg as tonnes
> >      kg_as_g = 1E+3
>
> >      def __init__(self):
>
> >          self.radius_of_earth = self.__class__.radius_of_earth
> >          self.days_as_yrs = self.__class__.days_as_yrs
> >          self.m2_as_ha = self.__class__.m2_as_ha
> >          self.g_as_tonnes = self.__class__.g_as_tonnes
> >          self.kg_as_tonnes = self.__class__.kg_as_tonnes
> >          self.kg_as_g = self.__class__.kg_as_g
>
> > usage something like
>
> >>> >from constants import Constants
> >>>> Constants.kg_as_g
> >>>> 1000.0
>
> No, simpler. No class statememt necessarily needed.
>
> module constants
> ----------------
>
> radius_of_earth = 6.37122E+6
> days_as_yrs = 1.0 / 365.25
> m2_as_ha = 1E-4  # metres squared as hectares
> g_as_tonnes = 1E-6  # grammes as tonnes
> kg_as_tonnes = 1E-3  # kg as tonnes
> kg_as_g = 1E+3
> # could also have code to load stuff from other files
>
> usage
> =====
>  >>> import constants
>  >>> constants.kg_as_g
> 1000.0
>
> Real example
>  >>> import math
>  >>> math.pi, math.e
> (3.141592653589793, 2.718281828459045)
>
> --
> Terry Jan Reedy

Cool! Thanks this seems straight forward, however if I do it this way
then once I change it (i.e. after reading user param file) I can't
pass the changed version to another module can i? Or am I being
stupid? Unless I do it my way I think

import cons
>>>print cons.kg_as_g
>>>1000.0
>>>cons.kg_as_g = 23.4
>>>print cons.kg_as_g

is fine.

But if I call import cons in another module it would be back to 1000.
right? Whereas if I do it as a class I can pass the adjusted instance?
E.g.

from constants import Constants
c = Constants()

I can then change "c" and pass this around?

Apologies if I have got that totally wrong!



More information about the Python-list mailing list