Instances?

Quinn Dunkan quinn at retch.ugcs.caltech.edu
Wed Aug 8 13:52:52 EDT 2001


On Tue, 31 Jul 2001 16:09:08 -0400, Angel Asencio <asencio at mitre.org> wrote:
>class Foo:
>    x = []
>    y = []
...
>Then, chenged the class to:
>
>class Foo:
>    def __init__(self):
>        self.x = []
>        self.y = []
...
> So, does not putting data attributes inside the __init__ would
>make them the equivalent to class variables on smalltalk or
>static variables in Java?

Sort of.  Everything after 'class Foo:' gets executed when 'class Foo' is
executed.  If you think about it, it has to, because the
'def method(self, ...)'s have to be executed then.  'def' is a statement just
like any other, as you can see if you do:

class Foo:
    print 'hi!'
    if foo:
        f = open('foo')
    else:
        q = 10

The important difference about things after a 'class X' is that assignments
will bind into the class namespace instead of the global or local namespace
(well, the class namespace is the local namespace, but, like a dictionary and
unlike a function, it isn't destroyed or inaccessible when the thread of
execution leaves it).  'def' statements count as assignment.

Anyway, when you ask an instance for an attribute, it first looks in the
instance's namespace.  If it doesn't find it there, it looks in its class'
namespace.  If it doesn't find it there, it looks in superclass' namespaces,
and if it's not there, it raises an AttributeError.  Since instances are a
seperate namespace from their classes (they have to be, or else instance
variables would all be class variables), when you bind in the instance
namespace you are shadowing things in the class namespace, the same way as you
shadow things in the global namespace or in a superclass' namespace.  Anyway,
the short of it is that:

class Foo:
    x = 5

f = Foo()
f.x = 10 # this creates a *new* x that shadows Foo's x
f.x
#-> 10
del f.x
f.x # now the old x is visible again
#-> 5

But as long as you don't create a new x, but merely modify the old x (like if
x were a list and you modified its contents), all the instances will continue
to see the same x (in the same way they all see the same methods) and it will
*act* like a class variable.

I think this is in the FAQ.



More information about the Python-list mailing list