Unclear On Class Variables

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Fri Jan 14 02:36:46 EST 2005


Antoon Pardon a écrit :
>>Well I find this a confusing behaviour on python's part. The fact
>>that instance.field can mean something different, depending on
>>where in a statement you find it, makes the behaviour inconsistent.
>>
>>I know people in general here are against declarations, but declarations
>>could IMO provide more consistency here and thus more obvious behaviour.
> 
> 
> Well just to show how confusing python can be, the following piece of
> code.
> 
> | class Spam:
> |   eggs = [2, 3]
> | 
> | 
> | sp1 = Spam()
> | sp2 = Spam()
> | 
> | print sp1.eggs, id(sp1.eggs)
> | print sp2.eggs, id(sp2.eggs)
> | print '--------------------'
> | 
> | sp1.eggs += [4,]
> |
> | print sp1.eggs, id(sp1.eggs)
> | print sp2.eggs, id(sp2.eggs)
> | print '--------------------'
> |
> | Spam.eggs = [3,5]
> |
> | print sp1.eggs, id(sp1.eggs)
> | print sp2.eggs, id(sp2.eggs)
> | print '--------------------'
> 
> Which produces:
> 
> [2, 3] 1075958860
> [2, 3] 1075958860
> --------------------
> [2, 3, 4] 1075958860
> [2, 3, 4] 1075958860
> --------------------
> [2, 3, 4] 1075958860
> [3, 5] 1075959084
> --------------------
> 

Well ... and could someone explain this behaviour ?
I don't catch it !

Pierre



More information about the Python-list mailing list