Class or Dictionary?

Martin De Kauwe mdekauwe at gmail.com
Mon Feb 14 03:44:22 EST 2011


On Feb 14, 7:12 pm, Terry Reedy <tjre... at udel.edu> wrote:
> On 2/13/2011 8:33 PM, Martin De Kauwe wrote:
>
> > 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?
>
> Wrong. There is one and only one module object, imported into (which
> means bound to a name in) as many modules as you want. If you change an
> attribute, it is changed for all. If you add attributes from any module,
> they are added for all, regardless of whether or not they have already
> imported it. No different from changing a list or dict with multiple names.
>
> The math module is read only. User python-coded modules are read-write.
>
> --
> Terry Jan Reedy

OK thanks I'll go over what I have done as I must have done something
stupid as I thought I tested it earlier and couldn't get it to work
like you suggested. Broadly this is how I am using it (incase it is
obvious, although perhaps it just works and I need to recheck). Apart
from that thanks for the modules idea it is very simple and seems to
be working nicely in principle.

from other_model import OtherSubModel
class Model:

    def __init__(self):

        # included other external modules (i.e. in other files)
        om = OtherSubModel()

    def run(self):
        # call other submodel and pass params
        om.run(params)

and the other file would look something like this

class OtherSubModel:
    def __init__(self):
        #some stuff

    def run(params):




More information about the Python-list mailing list