Class attribute or instance attribute?
Paul Watson
pwatson at redlinec.com
Mon Apr 28 23:36:44 EDT 2003
Thank you for your reply. I have finally gotten it that the attribute 'x'
is already a class attribute and not an instance attribute. It appears that
there can only be an instance attribute when someone says self.x or
instance.x. I used dir(C) and dir(self) to see what attributes existed. Is
there any other way to declare instance variables?
Thanks for everyone's help, including Mike.
"Michele Simionato" <mis6 at pitt.edu> wrote in message
news:2259b0e2.0304281329.12ac184b at posting.google.com...
> "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