On Mon, Feb 22, 2010 at 4:10 PM, C M Caine <cmca...@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
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor