__init__ style questions

Will McGugan will at willmcgugan.com
Mon Oct 2 12:42:01 CEST 2006

I am writting a Vector3D class as a teaching aid (not for me, for
others), and I find myself pondering over the __init__ function. I want
it to be as easy to use as possible (speed is a secondary

Heres the __init__ function I have at the moment.

class Vector3D(object):

    __slots__ = ('x', 'y', 'z')

    def __init__(self, x_or_iter=None, y=None, z=None):

        if x_or_iter is None:
            self.x = self.y = self.z = 0
        elif z is None:
            it = iter(x_or_iter)
            self.x = float(it.next())
            self.y = float(it.next())
            self.z = float(it.next())
            self.x = float(x_or_iter)
            self.y = float(y)
            self.z = float(z)

A Vector3D can be constructed in 3 ways. If no parameters are given it
assumes a default of (0, 0, 0). If one parameter is given it is assumed
to be an iterable capable of giving 3 values. If 3 values are given
they are assumed to be the initial x, y, z.

And now for the ponderings...

1) Is 'overloading' like this pythonic, or should I supply alternative

2) I convert the input values to floats, which seems convenient because
a Vector could be constructed with integers and other objects capable
of being converted to floats. Could this hide errors?

3) I like the constructing from an iterable, but it does mean that I
can do something crazy like Vector3D("123"). Could this also hide

4) This does seem like a good candidate for __slots__, since there will
could be large-ish lists of Vector3Ds. But is it a premature

If it was just for myself or other experienced programmers I wouldn't
be bothered about having the ability to do stupid things, because I
simply wouldnt do them! But I dont want to teach beginner programmers
bad habbits!

Any comments appreciated...

Will McGugan

More information about the Python-list mailing list