Unclear On Class Variables

Antoon Pardon apardon at forel.vub.ac.be
Thu Jan 13 08:33:02 EST 2005


Op 2005-01-13, harold fellermann schreef <harold.fellermann at upf.edu>:
> Hi Tim,
>
> If you have
>
> class Foo(object) :
> 	x = 0
> 	y = 1
>
> foo = Foo()
>
> foo.x # reads either instance or class attribute (class in this case)
>
> foo.x = val # sets an instance attribute (because foo is instance not  
> class)
>
> Foo.x = val           # sets a class attribute
> foo.__class.__x = val # does the same
>
> this might be sometimes confusing. IMHO, the following is especially  
> nasty:
>
> >>> foo = Foo()
> >>> foo.x += 1
> >>>
> >>> print foo.x
> 1
> >>> print Foo.x
> 0
>
> although the += operator looks like an inplace add it isn't.
> it is just syntactic sugar for foo.x = foo.x + 1.

Except is x belongs to a mutable class that implements the
+= operator as an inplace add.

Try the same but with x = [2]
and foo.x += [3]

-- 
Antoon Pardon



More information about the Python-list mailing list