Confused about class behavior

Erik Max Francis max at
Sat Sep 16 20:57:26 CEST 2000

Opinderjit wrote:

> class C:
>     color = "Green"
> I create two instances of class C, instance 'a' and 'b', and call the
> access the color attribute. The output is just as expected.
> When I do the following, both instances a and b were affected.
> >> C.color = 'Red'
> Is this correct?

That's correct.  An attributed defined in the class is common to all
instances.  This type of arrangement is similar to the `static' keyword
in C++, if you're familiar with it.

> Futher more, if I change the color attribute of one
> of
> the instance classes, b,  followed by changing the color of the base
> class, I get the follwoing:
> Because the color of instance b had already been changed, changing the
> color of the Base class didn't affect instance b, but it still
> affected
> instance a.

That is also correct.  If you explicitly replace the attribute in the
_instance_, then whatever setting in the class-specific variable will be
overridden, but that will not affect the class-specific variable and
other instances which have not been similarly overridden.  The behavior
you're seeing is correct.

 Erik Max Francis / max at /
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ The believer is happy; the doubter is wise.
\__/ (an Hungarian proverb)
    The laws list /
 Laws, rules, principles, effects, paradoxes, etc. in physics.

More information about the Python-list mailing list