question about globals vars...

Peter Hansen peter at engcorp.com
Fri Aug 2 22:52:26 EDT 2002


Lee Harr wrote:
> 
> class GameBoard:
>     def __init__(self):
>         GameBoard.height = 5
>         GameBoard.width = 10
> 
> class Avatar:
>     def __init__(self):
>         self.x = GameBoard.width / 2
>         self.y = GameBoard.height / 2
> 
> This is not a sterling example, but it gives an idea of what I
> am talking about. So, instead of passing the particular instance
> of the gameboard around all over the place, just put the vars
> some place that makes sense.
> 
> This might be bad style. In fact I was planning on asking here
> whether this is going to come back to haunt me in the future.
> 
> Any wisdom appreciated....

In my opinion this sort of thing is neither more nor less than
an increase in coupling, which is generally undesirable.  It
looks simple, but it does mean Avatar is tied to GameBoard,
perhaps unnecessarily.  In a non-trivial app, you probably
have GameBoard in another module, so now the module with Avatar
has to do an "import gameboard" or something, too.

A fairly simple and flexible idiom that would let you remove
the above coupling would be this:

class Avatar:
    def __init__(self, board):
        self.board = board
        self.x = board.width / 2
        self.y = board.height / 2
    def otherMeth(self):
        # here we can use self.board as needed, without
        # needing to know about GameBoard (or import it!)
        pass

-Peter



More information about the Python-list mailing list