[Baypiggies] Class methods as constructors?

Alex Martelli aleax at google.com
Tue Sep 2 21:12:07 CEST 2008

On Tue, Sep 2, 2008 at 11:28 AM, Charles Merriam
<charles.merriam at gmail.com> wrote:
> This may seem like a basic question.   Apologies if it's a known recipe.
> 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):

You missed the cls first argument.

>     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
> Is this the usual pattern?  Any gotchas?  Usually use "cls()" instead
> of "Spam()"?

Yes, yes (you need to have cls!) AND most emphatically yes (if you
don't call cls(), inheritance will produce pretty weird results).


More information about the Baypiggies mailing list