[Tutor] Object instances

John Fouhy john at fouhy.net
Mon Nov 7 01:43:41 CET 2005


On 07/11/05, DS <ds-python-tutor at sidorof.com> wrote:
> So, I can see the error of my ways.  I can also see that this behavior
> gives me an opportunity to globally change a value in all of the object
> 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.
>
> Can anyone point me in the right direction?

The difference is between class objects and class instances.

When you say "class Foo: ...", you are creating a class object.  When
you call a class object, you create an instance of that class.

Let's have a look:

>>> class Foo(object):
...   testList = []
...   print 'Foo class object being created now!'
...   def __init__(self):
...     self.testList2 = []
...     print 'Foo instance being initialised now!'
...
Foo class object being created now!
>>> Foo
<class '__main__.Foo'>

When I hit <return>, the python interpreted executed the class
definition.  This is why it printed out "Foo class object being
created now!".  This is also when it executed "testList = []". 
testList is an attribute of Foo:

>>> Foo.testList
[]
>>> Foo.testList.append(5)
>>> Foo.testList
[5]

On the other hand, the code in Foo.__init__ did not execute.  That
code will only execute when we create an instance of Foo.  So, Foo has
no testList2 attribute, because "self.testList2 = []" only happens in
__init__.

>>> Foo.testList2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: type object 'Foo' has no attribute 'testList2'

We can create an instance in the usual way, by calling the class object:

>>> f = Foo()
Foo instance being initialised now!

Now, we can get at testList2.

>>> f.testList2
[]

We can also get at testList in the same way --- but testList belongs
to the class, not the instance.

>>> f.testList
[5]
>>> f.testList is f.__class__.testList is Foo.testList
True

I guess the same thing happens with methods --- that there is only one
copy of each method --- but you don't notice, becuase when you call a
method on an instance, it gets passed the instance as the first
parameter.

Hope this helps!

--
John.


More information about the Tutor mailing list