[Tutor] class variables

Keith Winston keithwins at gmail.com
Fri Dec 20 08:04:49 CET 2013


I am a little confused about class variables: I feel like I've repeatedly
seen statements like this:

There is only one copy of the class variable and when any one object makes a
change to a class variable, that change will be seen by all the other
instances.
Object variables are owned by each individual object/instance of the class.
In
this case, each object has its own copy

But when I test, I see some interesting things: first (and this is
consistent with above) the class variables are created when the class is
defined, and can be used even without any instances of the class being
created.

Second, initially confusing but maybe I understand... there are pointers to
the class variables associated with every instance of the object, but if I
assign THOSE variables new values, it crerates new, "local"/instance
variables.

So:
Class.pi == 3.14  # defined/set in the class def
instance.pi == 3.14  # initially
instance.pi = 4  # oops, changed it
Class.pi == 3.14  # still
Class.pi = "rhubarb"  # oops, there I go again
instance.pi == 4  # still

Sorry if I'm beating this to a pulp, I think I've got it... I'm just
confused because the way they are described feels a little confusing, but
maybe that's because I'm not taking into account how easy it is to create
local variables...
-- 
Keith
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131220/90bcc99d/attachment.html>


More information about the Tutor mailing list