__init__ style questions

Duncan Booth duncan.booth at invalid.invalid
Mon Oct 2 07:03:11 EDT 2006


"Will McGugan" <will at willmcgugan.com> wrote:

> 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
> contstructors?

No it isn't Pythonic. Why not just require 3 values and move the 
responsibility onto the caller to pass them correctly? They can still use 
an iterator if they want:

    Vector3D(a, b, c)
    Vector3D(*some_iter)

Then your initialiser becomes:

def __init__(self, x=0, y=0, z=0):
    self.x, self.y, self.z = x, y, z

much cleaner and also catches accidental use of iterators.

Alternatively, insist on always getting exactly 0 or 1 arguments:

    Vector3D((a,b,c))
    Vector3D(some_iter)

def __init__(self, (x, y, z)=(0,0,0)):
    self.x, self.y, self.z = x, y, z

which is great if you already have lots of 3-tuples, but a pain otherwise 
to remember to double the parentheses.



More information about the Python-list mailing list