[Tutor] Object instances

Alan Gauld alan.gauld at freenet.co.uk
Mon Nov 7 05:33:35 CET 2005


>I had thought I was developing a clue regarding objects in Python, but I
> ran across an oddity today that I didn't expect.  It had seemed to me
> that once an instance was created, it would have a separate data pool
> from any other instance of the same object.

And this is true...

> It would share methods, of course, but the data assigned to it would
> be totally separate.

The data assigned top the instance is separate but you can also assign
data to classes. Such data is stored in "class variables". Class variables
are shared by all instances and indeed can be accessed even when no
instances exist. Methods are a special type of class variable. This all
comes under the black art known as "Meta Programming".

> I would like to understand why not.  I think I'm missing something kind
> of fundamental here.

Its very useful to know things about the class as an entirety. For example
a class variable can be used to keep track of the total number of instances
alive at any one time, or of standard lists of values that are valid for a
variable type (subsets of colors or max/min range values etc)

> The following is my toy example:

> In [1]: class test(object):
>   ...:     testlist = []

This is a class variable because its not distinguished by self (self is
unique to each instance).

> In [2]: c1 = test()
>
> In [3]: c1.testlist.append(0)
>
> In [4]: c2 = test()
>
> In [5]: c2.testlist
> Out[5]: [0]
> In this example, I create two instances of the object test, assigned
> data to c1.testlist and it shows up in the other instance, c2.

But you can also override that with

c2.testlist = [1,2,3]

c1.testlist
[0]
c2.testlist
[1,2,3]
c3 = test()
c3.testlist
[0]

So now c2 has its own copy of testlist...

> Typically, I have been assigning values within an object from being
> passed in via __init__, but it seemed like it wasn't really necessary
> for this particular kind of object.

It is if you want the values to be instance specific.

> In [10]: class test(object):
>   ....:     def __init__(self):
>   ....:         self.testlist = []

Now you are creating instance variables by assigning them with self.

> instances, if I ever had to do something like that.  I just don't have a
> clue as to why objects were designed this way.

Look up class variables (and static varoiables - their name in C++
and some other languages) on Google or  http://www.cetus-links.org

HTH<

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list