[Numpy-discussion] question about standalone small software and teaching

Gael Varoquaux gael.varoquaux at normalesup.org
Thu Apr 5 02:24:17 EDT 2007


On Wed, Apr 04, 2007 at 04:46:59PM -0700, Sebastian Haase wrote:
> Why do you define e.g. the Point class like this:
> class Point(object):
>     """ 3D Point objects """
>     x = 0.
>     y = 0.
>     z = 0.

> and not like this:
> class Point(object):
>     """ 3D Point objects """
>     def __init__(self):
>        self.x = 0.
>        self.y = 0.
>        self.z = 0.

> I thought in the first case, if one did "a = Point(); a.x = 6"  that
> from then on ANY new point ( "b = Point()" ) would be created with b.x
> being 6 -- because 'x' is a class attribute   and nor a instance
> attribute  !?

> This is obviously a beginners question - and I'm hopefully missing something.

Actually this raises quite subtle problems. 

The first syntax defines class attributes, and the second instance
attributes. Now in the given example there is no diference, because "x"
is a float, wich is immutable, so x get replaced each time it is
modified. I tend to use class attributes because I find that the class
definition is more readable, and they also survive to a forgotten
"super().__init__" in the init. Another reason is that traits are always
class attributes, so as I use traits a lot I tend to have the habit of
class attributes.

Now the subtle problems are illustrated by this code snippet:

++++++++++++++++++++++++
class Foo(object):
    a = [1, ]

f = Foo()
f.a.append(1)

g = Foo()

print g.a
++++++++++++++++++++++++

This will print out "[1, 1]". The reason is that the class attribute "a"
is a mutable that has been modified in place by the "append" operation.

I have seen beginners get tangled in these problems and I have recently
started avoided using class attributes when not necessary, so as to
avoid having to explain what are mutables, and class attributes... to
beginners, who often do not find all this easy to understand.

Gaël



More information about the NumPy-Discussion mailing list