The Occasional Occurence

My Take on Multiple Constructors

March 17, 2010 at 05:38 PM | categories: Python, Software, computing, General

I noticed the same question on c.l.p that Steve Ferg responded to on his blog. I was feeling too lazy to respond to the thread earlier but I thought I'd throw my idea up on the ol' blog before wrapping up for the day.

I think this is a classic use-case for class methods. Here is my implementation.

class Vector(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def from_sequence(cls, sequence):
        return cls(*sequence)

    def from_vector(cls, vec):
        return cls(vec.x, vec.y, vec.z)

    def __repr__(self):
        return "Vector(%s, %s, %s)" % (self.x, self.y, self.z)

if __name__ == '__main__':
    print Vector(1,2,3)
    print Vector.from_sequence([4,5,6])
    print Vector.from_sequence((7,8,9))
    v = Vector(10, 11, 12)
    print Vector.from_vector(v);

Here is the output from running the script:

Vector(1, 2, 3)
Vector(4, 5, 6)
Vector(7, 8, 9)
Vector(10, 11, 12)

I like the classmethod route because it is obvious what the code is doing, it makes it easy to add new from_\* methods and keeps the general __init__ method clean.