[Tutor] Scope and elegance

Kent Johnson kent37 at tds.net
Mon Jan 7 21:30:52 CET 2008


James Newton wrote:

> # So that I can call one of its functions from another instance 
> class Bar(object):
>     def doBar(self):
>         # I'd like be able to call a "global" object, but this fails:
>         # global name 'foo_instance' is not defined
> 	  return foo_instance.doFoo()

It fails because foo_instance is not a global; it is a local variable in 
the main() function. main() is a function too!

> def main():
       global foo_instance # This will do what you want
>     foo_instance = Foo()
>     bar_instance = Bar()
>     print bar_instance.doBar()


> I know that I can pass a pointer to foo_instance as a parameter to the
> Bar() call.

In general I would say that is a better design; I'm not generally a fan 
of globals.

> To put the question in context: in the Snakes and Ladders game that I am
> making, I have a board divided into 100 squares.  I want a Counter
> instance to know which position on the Board it should move to.  I may
> have several Counter instances, but only one Board instance.  Each
> Counter knows the index number of the square it should move to.  The
> Board instance knows how to convert that index number into a screen
> position.  I want the Counter instances to be able to ask the Board
> instance for that screen position.

Hmm. Why does a Counter need to know about screen position? It sounds 
like the Counter might be doing too much. Maybe the Counters should be 
attributes of the Board which can ask them their index numbers and do 
the appropriate drawing? Maybe the code that is drawing the counter 
should ask the Board where to draw it? I can't tell for sure but it 
sounds like your design might be inside out.

> Is it unPythonic of me to:
> a) Want to create the Board instance inside the main() function

That's OK

> b) Want the Board instance to be globally available so that
>    Counters and other objects can talk to it directly?

In general, globals are a bad idea in any language, not just Python.

> Or is there just a declaration that I have overlooked that can make an
> instance created inside a function visible inside any instance?

See above.

Kent


More information about the Tutor mailing list