code structure advise for a model

Peter Otten __peter__ at
Fri Feb 4 05:12:47 EST 2011

Martin De Kauwe wrote:

> I am translating some c++ code to python and just wanted to ask some
> advise on structure. The original has everything declared globally and
> nothing passed via function (I assume, but don't know, that this isn't
> just standard c++ practice!). So given this, I have a pretty much
> clean slate as I can't quite just copy the functions over. I was
> thinking something like this
> class Params:
>     def __init__(self, fname):
>         self.set_inital_condtions()
>         self.read_input_file(fname)
>     def set_inital_conditons(self):
>         self.some_parm = 0.0
>     def read_input_file(fname):
>         #read file, change initial params if specified
> then I thought I could pass this as an object to the model class
> class Model(Params):
>     def __init__(self):
>         # blah
>     def some_func(self):
>          if (Params.some_param == something):
>              foo
> OR this just a very bad way to structure it?

Your question is too low-level, and too technical. If you give a short 
description of what the program does and what options you see to structure 
it *in* *plain* *english* you'll get a clearer picture yourself and better 

In general use functions, and switch to classes only if you can demonstrate 
that they make the program's structure easier to understand.  Rather than 
use inheritance to split a "big beast that does it all" into smaller chunks 
aggregate smaller classes.

> The other thing I can't decide on is how to pass the parameters and
> variables through the class. So because of the way the original is
> written (everything is global), I could just inherit things, but it
> does means there is a lot of self. syntax. So I wondered if it might
> be better to pass things as function arguments? Any thoughts? I am
> also half considering other users from non-python backgrounds and what
> might seem very alien (syntax) to them.

Yes, passing data to functions/methods/classes explicitly is better than 
global state and also preferable over instance state.

More information about the Python-list mailing list