[Tutor] Strange list behaviour in classes

Benno Lang transmogribenno at gmail.com
Tue Feb 23 00:16:16 CET 2010


On 23 February 2010 07:10, C M Caine <cmcaine at googlemail.com> wrote:
> Or possibly strange list of object behaviour
>
> IDLE 2.6.2
>>>> class Player():
>        hand = []
>
>
>>>> Colin = Player()
>>>> Alex = Player()
>>>>
>>>> Players = [Colin, Alex]
>>>>
>>>> def hands():
>        for player in Players:
>                player.hand.append("A")
>
>>>> hands()
>>>>
>>>> Colin.hand
> ['A', 'A']
>>>> Alex.hand
> ['A', 'A']
>
> I would have expected hand for each object to be simply ['A']. Why
> does this not occur and how would I implement the behaviour I
> expected/want?

What you're accessing via Colin.hand and Alex.hand is actually
Player.hand, which is a class attribute. You want to set up attributes
on your instance objects instead; the standard way to do this is by
adding an __init__ method to your class:

class Hand:
    def __init__(self):
        self.hand = []

For more information, I suggest:
http://docs.python.org/tutorial/classes.html

HTH,
benno


More information about the Tutor mailing list