[Baypiggies] Class methods as constructors?

Shannon -jj Behrens jjinux at gmail.com
Wed Sep 3 02:37:06 CEST 2008


On Tue, Sep 2, 2008 at 1:47 PM, Aahz <aahz at pythoncraft.com> wrote:
> 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:
>>
>> @classmethod
>> 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
>>      i.add_to_production_queue(Process.chopping)
>>      return i
>
> You probably don't want to use assert -- that gets optimized away with
> .pyo files.
>
> 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.

Call me old school, but I still use factory functions (i.e. outside
the class) like Aahz, but what you're doing is perfectly fine.

-jj

-- 
Don't you wish you had a really clever sig like mine?
http://jjinux.blogspot.com/


More information about the Baypiggies mailing list