Class attribute or instance attribute?

Michele Simionato mis6 at pitt.edu
Mon Apr 28 17:29:33 EDT 2003


"Paul Watson" <pwatson at redlinec.com> wrote in message news:<vaqtlsqbi52j93 at corp.supernews.com>...
> When is an attribute a class attribute or an instance attribute?

I give you a subtle example:

class C(object):
      x=1 # class attribute
      def __init__(self):
          self.x=self.x # the class attribute becomes an instance attribute


c=C()

C.x=2

print c.x,C.x 

This code prints 1,2. You see that the line self.x=self.x is far
from being trivial: Python looks first for the self on the right,
looking for the instance attribute self.x: since it does not find anything,
it looks for the class attribute; then the class attribute
is assigned to the instance attribute on the left hand side.

If you forget the apparently useless self.x=self.x line, you get a 
different result:

class C(object):
      x=1 # class attribute
      def __init__(self):
          pass

c=C()

C.x=2

print c.x,C.x 

This prints 2,2, since the class attribute has been changed to 2
and c has no instance attribute.

Hoping-having-not-increased-your-confusion-ly,


                    Michele




More information about the Python-list mailing list