Unclear On Class Variables

Antoon Pardon apardon at forel.vub.ac.be
Thu Jan 13 14:26:05 CET 2005


Op 2005-01-13, Simon Brunning schreef <simon.brunning at gmail.com>:
> On 13 Jan 2005 07:18:26 EST, Tim Daneliuk <tundra at tundraware.com> wrote:
>> I am a bit confused.  I was under the impression that:
>> 
>> class foo(object):
>>         x = 0
>>         y = 1
>> 
>> means that x and y are variables shared by all instances of a class.
>> But when I run this against two instances of foo, and set the values
>> of x and y, they are indeed unique to the *instance* rather than the
>> class.
>
> I can see why you might think that:
>
>>>> class Spam(object):
> ... 	eggs = 4
> ... 
>>>> spam = Spam()
>>>> spam2 = Spam()
>>>> spam.eggs
> 4
>>>> spam2.eggs
> 4
>>>> spam.eggs = 2
>>>> spam.eggs
> 2
>>>> spam2.eggs
> 4
>
> But you are being mislead by the fact that integers are immutable.
> 'spam.eggs = 2' is *creating* an instance member - there wasn't one
> before. Have a look at what happens with a mutable object:
>
>>>> class Spam(object):
> ... 	eggs = [3]
> ... 
>>>> spam = Spam()
>>>> spam2 = Spam()
>>>> spam.eggs
> [3]
>>>> spam2.eggs
> [3]
>>>> spam.eggs.append(5)
>>>> spam.eggs
> [3, 5]
>>>> spam2.eggs
> [3, 5]
>

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.

-- 
Antoon Pardon



More information about the Python-list mailing list