Confused about class behavior
Mark Jackson
mjackson at wc.eso.mc.xerox.com
Sat Sep 16 14:01:14 EDT 2000
Opinderjit <bhellao at my-deja.com> writes:
> I don't seem to understand the following behavior. I create this class
> having one attribute, color, set to 'Green'
>
> class C:
> color = "Green"
Note color is a class variable. There is no code present that would
create instance attributes.
> I create two instances of class C, instance 'a' and 'b', and call the
> access the color attribute. The output is just as expected.
> >> a = C(); b = C()
> >> a.color; b.color
> 'Green'
> 'Green'
Since neither instance has any attributes of its own (look at the
output from 'dir(a)' at this point) you have examined C.color twice.
> When I do the following, both instances a and b were affected.
> >> C.color = 'Red'
> >> a.color; b.color
> 'Red'
> 'Red'
Neither instance is affected. Both continue to refer all inquiries on
to the base class.
> Is this correct? 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:
> >> b.color = 'Yellow'
This creates a new attribute, color, for the instance b.
> >> C.color = 'Blue'
> >> a.color; b.color
> 'Blue'
Since a still has no attributes, references the base class.
> 'Yellow'
The value referenced by the color attribute of the instance b.
Clearer now? To get the behavior you probably wanted, try this:
class D:
def __init__(self):
self.color = "Green"
--
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
Some circumstantial evidence is very strong,
as when you find a trout in the milk.
- Henry David Thoreau
More information about the Python-list
mailing list