[Tutor] Strange list behaviour in classes

Wayne Werner waynejwerner at gmail.com
Tue Feb 23 00:28:28 CET 2010


On Mon, Feb 22, 2010 at 4:10 PM, 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?
>
> Thanks in advance for your help,
> Colin Caine


This comes from the nature of the list object. Python lists are pass/shared
as reference objects. In your case, both Colin and Alex are pointing to the
Player object's copy of hands - they both get a reference to the same
object.

If you want to create different hand lists you could do something like this:

class Player:
    def __init__(self, hand=None):
        if isinstance(hand, list):
             self.hand = hand
        else:
             print "Player needs a list object for its hand!"


ex:

In [11]: Alan = Player()
Player needs a list object for its hand!

In [12]: Alan = Player([])

In [13]: Jim = Player([])

In [14]: Alan.hand.append(3)

In [15]: Jim.hand
Out[15]: []

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100222/a85d2e52/attachment-0001.html>


More information about the Tutor mailing list