[Tutor] Strange list behaviour in classes
C M Caine
cmcaine at googlemail.com
Wed Feb 24 00:27:42 CET 2010
On 22 February 2010 23:28, Wayne Werner <waynejwerner at gmail.com> wrote:
> 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
>
Thanks all (again). I've read the classes tutorial in its entirety
now, the problem I had didn't seem to have been mentioned at any point
explicitly. I'm still a fairly inexperienced programmer, however, so
maybe I missed something in there or maybe this is a standard
procedure in other OO programming languages.
More information about the Tutor
mailing list