classes and dictionaries

MRAB python at mrabarnett.plus.com
Wed Sep 15 20:36:41 EDT 2010


On 16/09/2010 01:13, Jason Swails wrote:
> Hello everyone,
>
> I'm encountering an issue in one of my Python classes that makes
> extensive use of dictionaries.  I was under the impression that each
> time an object was instantiated, all of its variables were created in a
> new section of memory, so that if you change the value of the variable
> in one instance, it left that variable's value in another instance
> alone.  In the object that I wrote, I have 3 different dictionaries:
> parm_data, pointers, and formats, all defined in the same place.  When I
> load 2 instances of this object, parm_data and formats each take on
> different values between the two objects (as they should), but for some
> reason pointers does not.  I've seen this problem with python2.6.4 and
> 2.6.1 (and I believe earlier versions as well, but I'm not sure).  I've
> attached a tarball with the relevant code and a sample script that shows
> what I mean.
>
> If anyone can tell me why the dictionary from 2 different objects are
> exactly the same for pointers, but are different for, e.g. parm_data and
> formats, that would be greatly appreciated.
>
When you bind to a name in the class namespace:

     class Example:
          foo = "class attribute"

the name is an attribute of the class.

If you want a name to be an attribute of an instance then you should
refer to the instance explicitly:

     class Example:
         def __init__(self):
             self.bar = "instance attribute"



More information about the Python-list mailing list