[Tutor] One shared object. class attribute or global variable?

Kent Johnson kent37 at tds.net
Sat Mar 4 02:20:40 CET 2006


Adam wrote:
> I've got a module that needs to share a pack of cards
> 
> pack = ["14s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "10s", "11s",
>     "12s", "13s", "14d", "2d", "3d", "4d", "5d", "6d", "7d", "8d", "9d", "10d",
>     "11d", "12d", "13d", "14c", "2c", "3c", "4c", "5c", "6c", "7c", "8c", "9c",
>     "10c", "11c", "12c", "13c", "14h", "2h", "3h", "4h", "5h", "6h", "7h", "8h",
>     "9h", "10h", "11h", "12h", "13h"]
> random.shuffle(pack)
> 
> do you think it is worth making a class with just this attribute or
> would this be a good place to use a global variable?

Some choices:
1. Pass the pack as a parameter to the functions that need to use it.
2. Make the pack a class attribute, maybe you can have a Game class. The 
functions that need it are good candidates for class methods.
3. Make pack a global variable

I would start with 1. If you have to pass it to a lot of functions, and 
the functions seem to cohere into a class, then maybe pick 2. The 
tipping point between 1 and 2 is a judgement call. I almost never use 
global variables except for constants and in short throwaway scripts.

By the way you may find that a Pack class makes sense, too, with methods 
like shuffle(), deal(howMany), isEmpty().

Kent



More information about the Tutor mailing list