[Tutor] Scope and elegance

Ricardo Aráoz ricaraoz at gmail.com
Tue Jan 8 00:58:32 CET 2008

James Newton wrote:
> Hi Python Practicioners!
> I'm trying to come to terms with how Python handles the scope of
> objects.  In particular, I'd like to create an instance of one class and
> make it available inside instances of other classes.  Something like:
> # Test 1-------------------------------------
> # I want a "global" instance of this class...
> class Foo(object):
>     def doFoo(self):
>         return "foo"

Puafff!!! Global = BAAAADDDD (unless, of course, there is no other way)

> I know that I can pass a pointer to foo_instance as a parameter to the
> Bar() call.  For example, this will work:


> I know that I can also create a global instance outside the main()
> function.  This will also work:


> 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.

Maybe you have a design issue here (it is usually the case if you have
to use globals). I would think it this way initially, a Board object has
(amongst other properties) a list property containing Piece objects, the
 Piece objects have the piece owner's name and the piece's position in
the board. The Board has a throwDice method which gets the dice result
and applies it to the nextPlayer (another property of Board, or of the
player's list which could be an object itself and manage nextPlayer),
nextPlayer would update it's position and ask the Board (it's container)
to update it's position. This comes off the top of my head so it will
certainly require redesign, but you get the idea, no globals. To start
the game you would call Board.play() which would have a loop till the
end of game is reached.


More information about the Tutor mailing list