[Tutor] One shared object. class attribute or global variable?
Alan Gauld
alan.gauld at freenet.co.uk
Sat Mar 4 14:21:03 CET 2006
> 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",
> ...
> 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?
Classes with single attributes are almost never the right thing.
The question is what does the class *do*?
What are its responsibilities within the application?
You've already suggested that it could shuffle itself.
Maybe it could deal a random card too?
Maybe it could tell you something about how many cards are left?
Or whether a particular card is in the pack?
In that case creating a class makers sense. Classes without behaviour
are rarely useful. Data without fiunction is rare. Data and function is a
class.
So if its only a bit of data themn sure make it a module level variable.
But ifd you are writing functions that operate on that data consider
makng it a class. Particul;arly if there could ever arise the need for
more than one pack - a game of Spider or Cribbage for example?
Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list