[Baypiggies] Class methods as constructors?
aahz at pythoncraft.com
Tue Sep 2 22:47:05 CEST 2008
On Tue, Sep 02, 2008, Charles Merriam wrote:
> I have a spot where I need a number of constructors for the same class
> and don't want to have too complicated an __init__ function. Using
> class methods seems like the cleanest code.
> x = Spam() # Simple case
> x = Spam.Pickled_Loaf(['Pimentos','Menthos'])
> x = Spam.Shake('chunky')
> with code in the Spam class like:
> def Picked_Loaf(additives, extra_gelatin = False):
> assert not ('Menthos' in additives and 'Diet Coke' in additives)
> i = Spam() # make an instance
> i.additives = additives
> return i
You probably don't want to use assert -- that gets optimized away with
Overall, I personally would be more inclined to use a factory function
or a slightly more complicated __init__ that dispatches, but there's
nothing wrong with what you're doing.
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
Adopt A Process -- stop killing all your children!
More information about the Baypiggies