Class-level variables - a scoping issue

Jean-Michel Pichavant jeanmichel at
Mon Oct 11 15:29:51 CEST 2010

John Nagle wrote:
>    Here's an obscure bit of Python semantics which
> is close to being a bug:
> >>> class t(object) :
> ...     classvar = 1
> ...
> ...     def fn1(self) :
> ...         print("fn1: classvar = %d" % (self.classvar,))
> ...         self.classvar = 2
> ...         print("fn1: classvar = %d" % (self.classvar,))

I don't think it's a bug.

None would name a class attribute and an instance attribute with the 
same name. So I'm assuming that you want to assign 2 to the *class* 
attribute (since it's named classvar :o) ).

You just did it wrong, self.classvar=2 creates the instance attribute 
classvar. This is easly fixed by using some well choosen coding rules:

when working with class attributes  within an instance either :

always write   t.classvar
always write   self.__class__.classvar

Problem solved. You could ask for python to reject self.classvar but 
that would break to OO lookup algo (== an instance has acces to its 
class attributes).


More information about the Python-list mailing list