Re: Global Variables in OOP and Python



newbie wrote:

Hello,

I have questions about global variables in OOP (in general) and Python
(in specific).  I understand (I think) that global variables are
generally not a good idea. However, if there are variables that need to
be accessed by a number of classes that exists in separate namespaces
(files), what would be the best way to do this?

So far, I have approached the problem by making the variables
attributes of one class and passing instances of the class as variables
to the other class' methods.

The other way I thought of is to create a separate class that consists
of the variables and to use the

from <file name> import *


That form is deprecated. Better (and certainly clearer to any reader of the code) is to leave them in the module.

Define a module, say Parameters, that defines any number of variables containing useful values. Then
import Parameters
wherever you want and refer to
Parameters.a
and
Parameters.b


You can even add runtime parameters (say options and paths from the command line) to the module during your initialization code, and those will be available wherever Parameters is imported:
Parameters.xyzzy = 'whatever'
Parameters.startDirectory = os.getcwd() # Get working directory at startup
(Even if the import of Parameters in some file occurs before the initialization code has a chance to run.)


Gary Herron

in all of the files (namespaces) where it is needed.

Is there a better way?

Are the two ideas presented above acceptable? If so, is one better than
the other from an OOP POV?




.



Relevant Pages

  • Global Variables in OOP and Python
    ... I have questions about global variables in OOP and Python ... be accessed by a number of classes that exists in separate namespaces ...
    (comp.lang.python)
  • Re: Global Variables in OOP and Python
    ... I have questions about global variables in OOP and Python ... be accessed by a number of classes that exists in separate namespaces ...
    (comp.lang.python)
  • Re: Public variables - when?
    ... and I have also used the mention global variables for reports. ... To talk about strict OOP within VFP is a ridiculous argument. ... of 40 or so system variables which are defined as: ...
    (microsoft.public.fox.programmer.exchange)
  • Re: Global Variables in OOP and Python
    ... > I have questions about global variables in OOP and Python ... > in all of the files (namespaces) where it is needed. ...
    (comp.lang.python)
  • Re: OOP with FORTRAN
    ... looking back at some very old numerical code OOP appears. ... > are grouped by and manipulate data in named COMMON blocks. ... In OOP the member variables do look a bit like global variables: ...
    (comp.lang.fortran)