[Tutor] Setting a global variable on class initialisation

Kent Johnson kent37 at tds.net
Thu Apr 27 17:17:00 CEST 2006


Max Russell wrote:
> Hello-
>  
> I know that overall Global variables are  bad idea, however, I have a 
> situation where on on initialisation of a class, I need to read in two 
> files and then populate two lists.

What do you mean by class initialization? If you want to read the files 
and populate the lists when the class is defined, it might work to do 
this at the module level. Then the lists would be populated when the 
module is first imported:

## mymodule.py
specialList = open('specialfile.txt').readlines()   # Whatever file 
processing you need goes here

class MyClass(object):
   # etc
   # do something with specialList


If you want to read the files when an instance is initialized, then put 
the code in the class __init__() method.

> The lists need to would appear to need to be outwith the class I am 
> working with and global.

?? What ??

Kent



More information about the Tutor mailing list