class instance scope

Steve Holden steve at holdenweb.com
Mon Jul 24 07:27:39 EDT 2006


Ritesh Raj Sarraf wrote:
> Hi,
> 
> I have a class defined in a file called foo.py
> 
> In bar.py I've imported foo.py
> In bar.py's main function, I instantiate the class as follows:
> 
> log = foo.log(x, y, z)
> 
> Now in main I'm able to use log.view(), log.error() et cetera.
> 
Correct. Because, having instantiated the class and retained a reference 
to the instance, the methods of the instance are available relative to 
the name containing the reference.

> But when I call the same method from some functions which are in
> bar.py, it fails giving me the following error:
> 
> NameError: global name 'log' is not defined
> 
Well, that's preumbaly because your

   log = foo.log(x, y, z)

statement was inside a function, and so the name "foo" was created in 
that function's local namespace rather than in the module's global 
namespace.

> 1) I tried lookng into the docs but couldn't find anything on instance
> scope.
> 2) How is such situation tackled ? Will I have to instantiate in every
> function ?
> 
The best thing to do would be to pass the instance in as an argument to 
the functions that need to manipulate it.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list