Op 2005-01-13, Simon Brunning schreef <[EMAIL PROTECTED]>: > On 13 Jan 2005 07:18:26 EST, Tim Daneliuk <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list